Djip Djip - 4 months ago 22
PHP Question

Operator '+=' behaves weird

My problem is that with this code I get 3, but as it looks to me I should get 1, but just don't have any idea how to fix it.

Example Code:

$counter = 0;
if (($counter = test2() !== false)) {
$counter += 2;
print $counter;
}

function test2() {
return -1;
}


Output: 3

If I do it the other way around it works fine and I will get -1.
Can someone please tell me what I'm doing wrong.

Example Code:

$counter = 0;
if (($counter = test2() !== false)) {
$counter -= 2;
print $counter;
}

function test2() {
return 1;
}


Output: 1

I hope that someone can explain this to me, because for me this is totally weird.

Answer

php treats this like:

$counter = 0;
if ($counter = (test2() !== false)) { //see?
    //so counter is equal to 1
    $counter += 2;
    print $counter;
}

function test2() {
    return -1;
}

this way is better:

$counter = 0;
if (($counter = test2()) !== false) { //see?
    //now counter is -1
    $counter += 2;
    print $counter;
}

function test2() {
    return -1;
}