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(); } } ?>
P粉7416783852023-09-08 14:19:49
Your else
block doesn't return anything, so unless you get the number 5 on the first try, it goes to the else
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 the else
block so that the returned value bubbles up to the initial call.
if ($number == 5) { return "ok"; } else { return get_number(); }
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 reach echo 'no';
P粉6966058332023-09-08 09:24:01
Please change the else condition from get_number();
to return get_number();
for recursive calls.
Also, why use 2 return statements in the if condition?
return "ok"; return false;
You can keep the first one and delete the second return statement.