16

How to use new version of Power operator instead of pow() in new version of php (5.6)? Like:

echo pow(2,3);

Why output of this line is 512 not 64?

2 ** 3 ** 2;
2
  • 3
    Please, read wiki RFC - there are more than enough samples there.
    – Alma Do
    Feb 15, 2014 at 20:30
  • 2
    Is it really so surprising how a binary operator works? Usually it's a op b. Feb 15, 2014 at 20:31

1 Answer 1

28

There is a sample ** operator in php 5.6 +

$i = 6;

$i **=2; //output 36

$out = $i ** 3 //output 46656

echo 2 ** 3 ** 2; // 512 (not 64) because this line evaluated right to left  => 2 ** (3 ** 2)
echo -3 ** 2; // -9 (not 9)
echo 1 - 3 ** 2; // -8
echo ~3 ** 2; // -10 (not 16)

** is better than pow(,) .
When you try to write a math algorithm. ** is a Powerful Operator.
there's no functional difference between it and pow.
power operator refrence

12
  • 10
    Exactly how is it "better"? Other than being a few less characters, there's no functional difference between it and pow. It's like saying "tool A is better than tool B, because tool A is PINK"
    – Marc B
    Feb 15, 2014 at 20:29
  • @Marc It may be better depending on the purpose it is used for. For example, if you were to take user input for an equation solver, and wanted to use exec, you could simply replace ^ with ** instead of needing to make sure to place that ) of pow() in the right place.
    – Anonymous
    Feb 15, 2014 at 20:37
  • @MarcB - Better for performance, no overhead of a function call but explicitly handled in exactly the same way as any other arithmetic operator
    – Mark Baker
    Feb 15, 2014 at 21:10
  • 17
    Being the author of ** I can tell you that it's different from pow() in the sense that it transparently supports GMP (if compiled); and it can be used wherever a constant expression is expected, such as a default value or class constant.
    – Ja͢ck
    Jul 21, 2014 at 14:30
  • 6
    Note that the output of the third line in the sample code should read $out = $i ** 3 //output 46656, not 216, since $i **= 2 assigns 36 to $i, thus $out = 36 ** 3. :) Nov 11, 2018 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.