3

I have noticed if a value is null i can increment it by one using ++$value but its not true about decrement , meaning --$value would return null , why?

$value = null;
echo ++$value; // 1
echo --$value; // null (I'm expecting -1)
alex
  • 7,551
  • 13
  • 48
  • 80

2 Answers2

10

Ref# language.operators.increment.php

Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
2

Think about it in a logical sense.

You can't take something away from nothing, but you can add something to nothing. Null is not 0, it is simply no value.

SGR
  • 403
  • 5
  • 16
  • Except PHP coerces null values to 0 in math operations. If you do `$val = null - 1` in PHP it works. If you do `$val--` it doesn't work. I thought decrement and increment were just shorthands. – Dean Or May 04 '22 at 20:51