php conditional loop error condition
P粉536532781
P粉536532781 2023-09-07 22:34:01
0
2
517

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粉536532781
P粉536532781

reply all(2)
P粉741678385

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粉696605833

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!