Php Switch Case无法按预期工作

I made a pretty stupid Logic Error in a very Basic PHP Script.

See u_mulders Answer for the Conclusion.

The Script accesses a $_GET[] Variable and should just determine if the Variable is set (wich works) and if its set to a value above 0 (this is not working as expected).

Here comes the "switch.php" File:

<?php

if($_GET["variable"]==NULL){
    die('Set $_GET["variable"] to use this Script!');
}

//Create Instance of $_GET["variable"] casted to Integer
$variable = (integer)$_GET["variable"];

//this var_dump displays that the $variable is succesfully casted to an Integer
var_dump($variable);

switch ($variable) {
    case ($variable > 0):
        echo "You entered $variable!";
        break;

    default:        
        echo "Either Your variable is less than 0, or not a Number!";
        break;
}

?>

Now I expected the first case-Statement to only run if $variable is greater than 0.

This is not the Case if I open the url: http://www.someserver.com/switch.php?variable=0

The Output is as follows:

.../switch.php:11:int 0

You entered 0!

I hope You can help me.

Thanks in advance.

So, $variable is 0, case $variable > 0 which is 0 > 0 is false.

Compare 0 and false. What do you get? Of course - true.

Rewrite your switch to:

// compare not `$variable` but result of some operation with `true`
switch (true) {           
    case ($variable > 0):
        echo "You entered $variable!";
        break;

    default:        
        echo "Either Your variable is less than 0, or not a Number!";
        break;
}
switch (true) {
    case ($variable > 0):
        echo "You entered $variable!";
        break;

    default:        
        echo "Either Your variable is less than 0, or not a Number!";
        break;
}

I think you misunderstood how does a switch works..

switch (VAR-TO-COMPARE){
    case VAL-TO-BE-COMOARED: do something
}

So what is going on in your script is you are comparing the integer value stored in $variable (0 in your example) with a Boolean value Wich is the result of the Boolean equation $variable > 0. Inside the case, your integer value is implicitly casted to Boolean TRUE value, so if you insert a number your switch will always go to the first case of your switch.

You can use an if statement Wich is both more readable and efficient

if ($variable > 0){
    do something
} else{
    do something else
}

You cannot use comparison operator in a switch case. Refer to the php manual. You can use if statement to do what you looking for.

if($variable > 0){
  echo "You entered $variable!";
}else{
  echo "Either Your variable is less than 0, or not a Number!";
}