Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Use the source, Luke</strong></p> <p>As usual, the answer lies in the source. PHP uses the following two functions internally to perform the increment and decrement operations:</p> <p><a href="http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#1794" rel="noreferrer"><code>ZEND_API int increment_function(zval *op1)</code></a></p> <p><a href="http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#1845" rel="noreferrer"><code>ZEND_API int decrement_function(zval *op1)</code></a></p> <p>These operations modify the <code>op1</code> argument based on its type (<code>NULL</code> is a type); inside <code>increment_function()</code> you can see the following branch <a href="http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#1809" rel="noreferrer">in the code</a>:</p> <pre class="lang-c prettyprint-override"><code>case IS_NULL: ZVAL_LONG(op1, 1); break; </code></pre> <p>The above code changes the type of <code>op1</code> into a number and sets its value to <code>1</code>.</p> <p>Conversely, <code>decrement_function()</code> offers no such branch and therefore the <a href="http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#1884" rel="noreferrer">default action</a> will be performed:</p> <pre class="lang-c prettyprint-override"><code>default: return FAILURE; </code></pre> <p>Running this code won't actually yield any observable failure, because the return values are absorbed in the Zend VM, but the variable definitely isn't updated either.</p> <p><strong>It's not a bug(tm)</strong></p> <p>You may be surprised to know that this behaviour, including that for boolean values, is actually <a href="http://php.net/manual/en/language.operators.increment.php" rel="noreferrer">documented</a>:</p> <blockquote> <p><strong>Note:</strong> The increment/decrement operators do not affect boolean values. Decrementing <code>NULL</code> values has no effect too, but incrementing them results in <code>1</code>.</p> </blockquote> <p>Regarding booleans:</p> <pre><code>$a = true; var_dump($a--); // true $a = false; var_dump($a++); // false </code></pre> <p>Regarding strings:</p> <pre><code>$letter = 'A'; var_dump(++$letter); // B var_dump(--$letter); // B </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload