skip to Main Content

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.

enter image description here

<?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


  1. Please change your else condition from get_number(); to return get_number(); to make recursive call.

    Also, why you are using 2 return statements in if condition ?

    return "ok";
    return false;
    

    You can keep first one, remove second return statement.

    Login or Signup to reply.
  2. Your else block doesn’t return anything, so unless you get the number 5 on the first attempt, it will go to the else 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 the else-block as well to make the returned alue bubble up all the way to the initial call.

    if ($number == 5) {
        return "ok";
    }
    else {
        return get_number();
    }
    

    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 reach echo 'no';

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. 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(); to return get_number();

    <?php
    
    if (get_number() == "ok") {
        echo "ok";
    } else {
        echo "no";
    }
    
    function get_number()
    {
        $number = rand(1, 10);
        echo $number;
        if ($number == 5) {
            return "ok";
        } else {
            return get_number(); // Return the result of the recursive call
        }
    }
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search