Please tell me, if the condition is true, why does it not display "ok"? I don't understand why it displays "No" 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(); } } ?>
Your
else
block doesn't return anything, so unless you get the number 5 on the first try, it goes to theelse
block, which calls itself, but does not actually return any value to the initial call.If the function returns nothing, you will get
NULL
.Also add a
return
statement in theelse
block so that the returned value bubbles up to the initial call.BTW, I hope this isn't real code but just some testing, because it's basically just an overly complicated way of echoing
ok
. It should never reachecho 'no';
Please change the else condition from
get_number();
toreturn get_number();
for recursive calls.Also, why use 2 return statements in the if condition?
You can keep the first one and delete the second return statement.