Search code examples
phpswitch-statementcaseboolean-expression

Why is the corresponding statement not executed even if echo empty($location) prints out 1


echo empty($location);
switch($location){
    case (empty($location)):
expression 1;
    break;
    case ($location%10000==0):
expression 2;
    break;
    case ($location%100==0):
expression 3;
    break;
    default:
    expression 4;
    break;

}

When I echo empty($location), it prints out 1, why is expression 1 not executed?


Solution

  • You're not using switch statements properly. The way they work is to compare each case value against the initial switch value.

    In your case, let's pretend $location = null;

    echo empty($location);    // true: null is considered empty.
    
    switch ($location) {
        case empty($location) :    // this performs the check:
                                   // $location == empty($location)
                                   //      null == true ==> false
    

    so that's why it doesn't run..

    I'd recommend sticking to if .. else in this case.