Simple Question from a true beginner

I’m learning PHP and was experimenting with progressively harder code. (Obviously, I haven’t gotten very far.) I seem to be having trouble with functions, as the following code outputs ‘3’ instead of ‘81’ (the sought answer).

Could someone explain what I did incorrectly? The language I am most familiar with is Java.

Thanks!!

[php]

<?php function power($base, $power) { $result = 0; if($power = 0) { $result = 1; } else { $result = $base; for($i=0; $i<$power; $i++) { $result = $result * $base; } } return $result; } echo power(3,4); ?>

[/php]

Oh, I now realize that the condition for my ‘for’ loop should be ‘$i<$power-1’ but I still have the same problem as before.

line…
[php]
if($power = 0){
[/php]
should be…
[php]
if($power == 0){
[/php]
one = will change the left value to the right value.
two == compares the left value to the right value.
Three equal signs in PHP is also a comparison operator but looks not only at the value but also looks at the type of the variables.

though you could also do:
[php]
function powers($base, $power){
$base = $_GET[‘base’];
$power = $_GET[‘power’];
$result = 0;
if($power == 0){
$result = 1;
}else{
$result = pow($base,$power);
}
return $result;
}
echo powers(3, 4);
[/php]

Wow! I can’t believe I made such an obvious error! I would’ve seen it instantly if I hadn’t written it. Thanks for the correction and the alternative method.

Nick :smiley:

you quite welcome, glad to have help’d out.

Sponsor our Newsletter | Privacy Policy | Terms of Service