Skip to content
Advertisement

How I can create my own pow function using PHP?

I want to create a function in which I put two values (value and its power – Example function: multiply(3, 3) result 27). I have tried so far but failed, I have searched using Google but I have been unable to find any result because I don’t know the name of this function.

What I want exactly:

3,3 => 3 x 3 x 3 = 27
4,4 => 4 x 4 x 4 x 4 = 256

What I tried:

function multiply($value,$power){
    for($x = 1; $x <= $value; $x++ ){
        return $c = $value * $power;
    }   
}
echo multiply(3,3);

Advertisement

Answer

Oopsika, couldn’t have asked a more obvious question. Use the built-in function named pow (as in a lot of languages)

echo pow(3, 3);

Edit

Let’s create our own function.

function raiseToPower($base,$exponent)
{
    // multiply the base to itself exponent number of times
    $result=1;
    for($i=1;$i<=$exponent;$i++)
    {
      $result = $result * $base;  
    }
    return $result;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement