Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use switch with integer 0 in PHP?

having the integer 0 as switch parameter will take the first result "foo":

$data=0; // $data is usually coming from somewhere else, set to 0 here to show the problem
switch ($data) :
    case "anything":
        echo "foo";
        break;
    case 0:
        echo "zero";
        break;
    default: 
        echo "bar";
endswitch;

How do I change this, so the switch will write "zero" as expected?

like image 422
rubo77 Avatar asked Nov 11 '13 07:11

rubo77


Video Answer


2 Answers

Switch/case statement uses "loose-comparison" (i.e. ==. in this case, 0 also means false and 1 also means true. (http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose)

To avoid this problem, two solutions:

1) As suggested by @zzlalani, add quotes.

   case '0': ...

2) Explicitly cast the switch statement to force a strict comparison (===)

    switch((string)($data)) { ... }
like image 41
Antoine Avatar answered Oct 26 '22 07:10

Antoine


The switch/case statement uses loose comparison, and, like it or not, 0 == "anything" is true:

Comparison Operators

[...] If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. [...]

var_dump(0 == "a"); // 0 == 0 -> true

One solution is to change all case statements to string, and do a string comparison:

$data = 0;
switch ((string) $data): ## <- changed this
    case "anything":
        echo "foo";
        break;
    case "0":            ## <- and this
        echo "zero";
        break;
    default: 
        echo "bar";
endswitch;
like image 95
Salman A Avatar answered Oct 26 '22 06:10

Salman A