Raising to power in PHP

10,124

Solution 1

The caret is the bit-wise XOR operator in PHP. You need to use pow() for integers.

Solution 2

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

Solution 3

The ^ operator is the bitwise XOR operator. You have to use either pow, bcpow or gmp_pow:

var_dump(pow(10, -0.01));  // float(0.977237220956)
Share:
10,124
Kuroki Kaze
Author by

Kuroki Kaze

Techpriest.

Updated on June 05, 2022

Comments

  • Kuroki Kaze
    Kuroki Kaze almost 2 years

    Well, i need to do some calculations in PHP script. And i have one expression that behaves wrong.

    echo 10^(-.01);
    

    Outputs 10

    echo 1 / (10^(.01));
    

    Outputs 0

    echo bcpow('10', '-0.01') . '<br/>';
    

    Outputs 1

    echo bcdiv('1', bcpow('10', '0.01'));
    

    Outputs 1.000....

    I'm using bcscale(100) for BCMath calculations.

    Excel and Wolfram Mathematica give answer ~0,977237.

    Any suggestions?

  • Kzqai
    Kzqai over 9 years
    This all makes me sad. The unary operator precedence and the choice of operator, so close to * as to be easily typo-ed.