views:

39

answers:

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

A: 

The empty function returns a boolean value of 1 or 0 http://uk3.php.net/empty

Whereas the switch / case statements check whether a variable holds a certain value and execute an expression depending on that

In you case, expression 1 should be executed if the value of $location==1 (you effectively asked for that when you typed switch($location)),

So the logic of your above code is:

if $location==1, execute expression 1
if $location%10000==0, execute expression 2
etc. etc.

is the value of $location==1?

pǝlɐɥʞ
+1  A: 

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.

nickf
But there is no problem with case ($location%10000==0):expression 2; break; case ($location%100==0):expression 3;
Steven
ok, well think it through: `$location = 20000`, therefore `$location % 10000 == 0)` is `true`. `20000 == true` is true, therefore it works. If you really want to stick with this format for some reason change your switch statement to be: `switch (true) {`
nickf
Your answer and comments are very helpful. Thank you, @nickf.
Steven
A: 

A switch statement is not the same as an if/else statement. Switch statements are looking for specific values. If it finds the value specified in a given case statement, it runs the code after that case statement.

The following code:

switch($x)
    case 1:
        // some stuff
        break;
    case 2:
        // some other stuff
        break;
    default:
        // some more stuff
        break;

Is the equivalent of this code:

if($x == 1){
    // some stuff
}
elseif($x == 2){
    // some other stuff
}
else{
    // some more stuff
}

Basically, switch statements are shortcuts for if/elseif/else blocks where you're checking for a single variable's equality against a bunch of possibilities.

Since empty() returns 0 or 1, your first case will run if $location is 1 (if $location is empty) or 0 (if $location isn't empty). It's almost like you've written the following:

elseif($location == empty($location)){ ...

Make sense? Instead of using a switch statement, you probably want the following:

if(empty($location)){
    // ...
}
elseif($location % 10000 == 0){
    // ...
}
// ...
jboxer