please tell me why not display "ok" if the condition is true?
I can not understand why "no" is displayed if the condition is triggered.
<?php if (get_number() == "ok") {
echo "ok";
}
else {
echo "no";
}
function get_number() {
$number = rand(1, 10);
echo $number;
if ($number == 5) {
return "ok";
return false;
}
else {
get_number();
}
} ?>
4
Answers
Please change your else condition from
get_number();
toreturn get_number();
to make recursive call.Also, why you are using 2 return statements in if condition ?
You can keep first one, remove second return statement.
Your
else
block doesn’t return anything, so unless you get the number 5 on the first attempt, it will go to theelse
block, that calls itself but won’t actually return any value to the initial call.If a function doesn’t return anything, you will get
NULL
instead.Add a
return
statement in theelse
-block as well to make the returned alue bubble up all the way to the initial call.Btw, I hope this isn’t real code but just some test, since it’s basically just an overcomplicated way of echoing
ok
. It should never be able to reachecho 'no';
rand(1, 10) this will return a random number generated like this 183995 and you added condition that if ($number == 5) then return "ok" but in your case, it will not satisfy and always goes in else condition so you get no as output
Let me explain it. You must know every function must return something unless it’s
void
.In the else block, where you make a recursive call to
get_number()
, you are not returning the result of the recursive call.Change
get_number();
toreturn get_number();