Why “switch(true){}” in php with a strange logic?

后端 未结 5 1507
醉酒成梦
醉酒成梦 2020-12-30 03:38
switch(false) {
    case \'blogHitd\':
        echo(\'ffffd\');
        break;
    case false:
        echo(\'bbbb\');
        break;
    default:
        echo \'alert         


        
5条回答
  •  春和景丽
    2020-12-30 04:30

    In this scenario the switch only runs the first valid case.

    It is useful in the case that you have more than one possible answer but you want to run only the first one. For example:

    switch(true){
     case 1 == 2:
       echo '1 == 2';
       break;
    
     case 2 == 2:
       echo '2 == 2';
       break;
    
     case 3 == 3:
       echo '3 == 3';
       break;
    
     case 4 == 1:
       echo '4 == 1';
       break;
    }
    

    The output: 2 == 2

    Both the second and third cases are true, but we only get the second (which is the first TRUE).

提交回复
热议问题