Dmitry Lezhnev
Dmitry Lezhnev

Reputation: 884

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!

Upvotes: 2

Views: 481

Answers (4)

Lorenz Meyer
Lorenz Meyer

Reputation: 19895

I'm pretty sure, that the documentation is wrong here.

Operator ** has greater precedence than ++.

This statement seems in contradiction with how grouping obeys to operator precedence.

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation.

In fact if we group ** before ++, we obtain ++($a ** 2), like it is stated in the question. But this expression is not even valid, because the ++ operator can only be used for a variable, but not for an expression.

The fact that ++ is only valid for a variable implies that no operator with two operands can have higher precedence.

Upvotes: 1

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

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

Upvotes: 4

Sander Visser
Sander Visser

Reputation: 4320

What seems to happening is that the Post/Pre increments are evaluated outside the operation. So the ** is executed and the result is returned.

  • For a post increment the $a variable is updated after the operation.
  • For a pre increment the $a variable is updated before the operation.

So the documentation

Operator ** has greater precedence than ++.

Seems a little bit strange to me.

After some searching this is also mentioned in the comments: http://php.net/manual/en/language.operators.increment.php#119098

Ow and in the documentation itself.

<?php
// POST
$a = 2;
echo($a ** 2);      // 4
echo(PHP_EOL);
echo($a++ ** 2);    // 9
echo(PHP_EOL);
echo($a);           // 3
echo(PHP_EOL);
echo(PHP_EOL);

// PRE
$a = 2;
echo($a ** 2);      // 4
echo(PHP_EOL);
echo(++$a ** 2);    // 4
echo(PHP_EOL);
echo($a);           // 3
echo(PHP_EOL);
echo(PHP_EOL);

Upvotes: 0

Gabriel Caruso
Gabriel Caruso

Reputation: 869

Spaces, this is why!

++ $a ** 2 is different from ++$a ** 2, that is also different from ++$a**2

Upvotes: -1

Related Questions