php - Why decremented of NULL not negative in this array? -


i have tried code

$a = array_fill(0, 4, null); $a[0]++; ++$a[1]; $a[2]--; --$a[3]; var_dump($a); 

result:

array(4) {     [0]=> int(1)     [1]=> int(1)     [2]=> null     [3]=> null } 

why value of 2 , 3 index not negative?

use source, luke

as usual, answer lies in source. php uses following 2 functions internally perform increment , decrement operations:

zend_api int increment_function(zval *op1)

zend_api int decrement_function(zval *op1)

these operations modify op1 argument based on type (null type); inside increment_function() can see following branch in code:

case is_null:     zval_long(op1, 1);     break; 

the above code changes type of op1 number , sets value 1.

conversely, decrement_function() offers no such branch , therefore default action performed:

default:     return failure; 

running code won't yield observable failure, because return values absorbed in zend vm, variable isn't updated either.

it's not bug(tm)

you may surprised know behaviour, including boolean values, documented:

note: increment/decrement operators not affect boolean values. decrementing null values has no effect too, incrementing them results in 1.

regarding booleans:

$a = true; var_dump($a--); // true $a = false; var_dump($a++); // false 

regarding strings:

$letter = 'a'; var_dump(++$letter); // b var_dump(--$letter); // b 

Comments