Search code examples
pow

how can I make a function like pow in php


I wanted to make function that could work like pow() but I wasn't succeed . it's my code:

function ipow($rishe,$tavan){
  if (is_numeric($rishe) & is_numeric($tavan)) {
    for ($i=1; $i <= $tavan ; $i++) {
      $hesab = 1;
      $hesab *= $rishe;
      return $hesab;
    }
  } else {
    $invalid_rishe = gettype($rishe);
    $invalid_tavan = gettype($tavan);
    echo "This function gives 2 numeric prameter.";
  }
}
echo ipow(2,3);

echo ipow(2,3);

cane someone help me to make a function like pow()?


Solution

  • You were pretty close, you need to take 2 lines out of the for loop, like this:

    Your code fragment

    for ($i=1; $i <= $tavan ; $i++) {
      $hesab = 1;
      $hesab *= $rishe;
      return $hesab;
    }
    

    First of all, the return statement stops execution the first time it executes, effectively doing just once the multiplication. Also you want to initilize $hesab = 1 outside the loop, because there it's reinitializing on each loop iteration.

    Should be like this

    $hesab = 1;
    for ($i=1; $i <= $tavan ; $i++) {
      $hesab *= $rishe;
    }
    return $hesab;