skip to Main Content

Why is the below code printing out both "yes" and! "no" ?

Only if I add ‘break;’ to the TRUE case, it only prints out "yes" , but that shouldnt change the fact that the case FALSE, is not going to run, $arr is always an array.

Am I doing something wrong?

$arr=[1,2];
switch (is_array($arr)) {
    case TRUE:
        print "yes";
        //break;
    case FALSE:
        print "no";
}

2

Answers


  1. Well… the switch statement requires a break after each case, since by default it’ll will try to execute the next case; as said on w3school :

    If there is a match, the block of code associated with that case is
    executed. Use break to prevent the code from running into the next
    case automatically.

    Now about the expected return value, the condition will return a boolean indeed, but not in the ALPHA format, but rather in a NUMERIC boolean, by that I mean it’ll return 1 if verified and nothing if not, as w3school says

    This function returns true (1) if the variable is an array, otherwise
    it returns false/nothing.

    So you might want to adjust your expected output from TRUE to 1 and FALSE to ”

    $arr=[1,2];
    switch (is_array($arr)) {
        case 1:
            print "yes";
            break;
        case '':
            print "no";
            break;
    }
    
    Login or Signup to reply.
  2. The reason why the code is printing out both "yes" and "no" is because in a switch statement in PHP, if there is no break statement at the end of each case block, the execution will "fall through" to the next case block, regardless of whether the condition, in that case, the block is true or false.

    In this case, since $arr is an array, the condition in the first case block (TRUE) is true, and "yes" is printed. However, since there is no break statement, the execution falls through to the next case block, which prints out "no" because it is the default case.

    If you add the break statement to the end of the first case block, the execution will stop after "yes" is printed, and "no" will not be printed. Here’s the updated code:

    $arr=[1,2];
    switch (is_array($arr)) {
        case TRUE:
            print "yes";
            break;
        case FALSE:
            print "no";
    }
    

    This will only print out "yes" since the execution will stop after the first case block.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search