In programming languages like PHP, there are no equations; there are only expressions.
In algebra, this equation is solvable.
By subtracting 3x from both sides and dividing both sides by -2, it is revealed that x is 2.
However, in PHP, a similar statement is treated differently.
PHP does not "solve for x". The $x on the right is not necessarily equal to the $x on the left. If $x is not given a value before this statement, its assumed value is equivalent to 0. The arithmetical operations reduce the expression on the right to -4. That number is then assigned to the $x on the left.
Whereas the algebra equation is a puzzle to be solved, the PHP statement is a set of instructions to be followed.
To solve an equation like
programmatically, you can...
- ...create a way to parse the symbols and "undo" the operations to isolate a single variable. In the example, the x can be isolated by dividing by 7 to undo the multiplication. Reducing the mirrored expression (21 / 7) reveals the value of x.
- ...brute-force potential values until both sides of the equation are equal (or close to equal). In the example, {0, 1, 2} might be tried as values of x before it is found that 3 makes both sides equal 21. You might try something like a binary search to close in on the correct answer quicker.