Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain why PHP switch case is always executing case 0 in this code

Can someone please explain why the case "a" is never reached in below code and why it will always execute case 0

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
like image 472
Aditya Hajare Avatar asked Jan 12 '17 03:01

Aditya Hajare


Video Answer


2 Answers

PHP, like JavaScript or Perl, is a loosely-typed language and will attempt to guess what you want to do. In this case, it changed your string to the closest integer it could find, which is zero. In other words, "a" == 0 is a true statement in PHP.

More on this topic can be found in the PHP documentation. I suggest you typecast the value in the switch statement, or replace it with an if/elseif/else construct.


As of PHP 8.0, this behaviour has changed and now the integer value will always be changed to a string before comparison between the two types. Strictly typing and comparing your variables remains the recommended practice, however.

like image 123
miken32 Avatar answered Oct 10 '22 23:10

miken32


You can not used mix-cases in a switch statement as PHP will interpret the meaning of what you mean.

In layman's terms, it will try to find the 'value of "a"' which is not defined to the processor, and hence is 0 in this case.

Same will go for the code below:

<?php

$x = "a";
switch($x)
{
    case "c":
        echo "c";
    break;

    case 1:
        echo "1";
    break;  

    case 0:
        echo "0";
    break;

    case "a":
        echo "a";
    break;

    case false:
        echo "false";
    break;

    default:
        echo "def";
    break;
}

?>

Documentation is available at PHP.net

like image 25
Ruslan Abuzant Avatar answered Oct 10 '22 23:10

Ruslan Abuzant