PHP 5.6 finally introduced an innate power operator, notated by a double asterisk (**
) - not to be confused with ^
, the bitwise XOR operator.
Before 5.6:
$power = pow(2, 3); // 8
5.6 and above:
$power = 2 ** 3;
An assignment operator is also available:
$power = 2 ** 2;
$power **= 2; // 8
Through many discussions and voting, it was decided that the operator would be right-associative (not left) and its operator precedence is above the bitwise not operator (~
).
$a = 2 ** 3 ** 2; // 512, not 64 because of right-associativity
$a = 2 ** (3 ** 2); // 512
$b = 5 - 3 ** 3; // -22 (power calculated before subtraction)
Also, for some reason that does not make much sense to me, the power is calculated before the negating unary operator (-
), thus:
$b = -2 ** 2; // -4, same as writing -(2 ** 2) and not 4