Why does the decrementing operator in PHP work in this way?

40 Views Asked by At

The following code:

$arr = array(1, 2, 3, 4, 5);
$i = 5;
while($i >= 1){
    var_dump($i);
    var_dump($arr[--$i]);
}

has the following output:

int(5)
int(5)
int(4)
int(4)
int(3)
int(3)
int(2)
int(2)
int(1)
int(1)

but if we replace the two lines within the while loop with the single line:

var_dump($i == $arr[--$i]);

the code has the following output:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

The first output shows that $i and $arr[--$i] are equal.

The second output shows that $i and $arr[--$i] are not equal.

Why this discrepancy? What am I missing?

0

There are 0 best solutions below