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 (which 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 successfully 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;
}