Search code examples
phpoperatorsoperator-precedence

PHP exponentiation operator precedence


I read the PHP.net docs which states:

Operator ** has greater precedence than ++.

But when I run this code I get unexpected output:

<?php
$a = 2;
echo(++ $a ** 2); 
// output: 9, means: (++$a) ** 2
// expected: 5, means: ++($a ** 2)

Can you help me get it clear why that happens? Thanks!


Solution

  • This is because ++$a is a pre-increment, and $a++ is a post-increment.

    You can read more about this here

    Also,

    Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

    From: PHP Operator Precedence