Search code examples
phpoperators

Operators = vs. == in PHP


I am learning basic PHP from a book, and from what I read, = is an assignment operator, and == is a comparison operator. So...

$x = 5;
$x == 5: true

...makes sense. However, the book gives an example which confuses me:

if (++$x == 10)
    echo $x;

Why ==? Aren't we trying to say "if ++$x equals 10, then echo $x"...? Then that would seem like: if (++$x = 10). The former would be like asking a question inside a conditional statement, which would be illogical or redundant.


Solution

  • == means equality, so the conditional reads as:

    If pre-incremented $x equals 10, echo $x

    Single = is assignment, where a variable is set to contain a value:

    $word = 'hello';
    $number = 5;
    // etc.
    
    echo "I said $word $number times!";
    

    Regarding the increment opperators:

    You'll see things like ++$x and $i-- as you learn PHP (and/or other languages). These are increment/decrement operators. Where they're positioned in relation to the variable they're operating on is important.

    If they're placed before the variable, like ++$x, it's a pre-increment/decrement. This means the operation is performed before anything else can be done to the variable. If it's placed after, like $x++, it's a post-increment/decrement, and it means that the operation is performed afterward.

    It's easiest to see in an example script:

    $x = 5;
    
    echo ++$x; // 6
    echo $x++; // ALSO 6
    echo $x; // NOW 7