Aditya Hajare
Aditya Hajare

Reputation: 1391

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;
}

Upvotes: 6

Views: 2835

Answers (4)

miken32
miken32

Reputation: 42712

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.

Upvotes: 7

BizzyBob
BizzyBob

Reputation: 14740

The reason for this is because switch uses a loose comparison ==

That said:

if ("a" == 0) // TRUE
if ("a" == true) // TRUE

Pretty much anything else will evaluate to false. (except "a" == "a")

So, if you have the need to compare against both strings and integers, you should just convert to string for the comparison.

//$var = "a";
$var = 0;

$var = strval($var);
switch ($var) {
    case '0':
        echo "0";
        break;
    case 'a':
        echo "a";
        break;
}

Upvotes: 2

mith
mith

Reputation: 1700

The variable type used on case() should be same type used in switch().

   <?php
    switch ("a") {
       case "0":
          echo "0";
          break;
       case "a": // never reached because "a" is already matched with 0
          echo "a";
          break;
    }

For integer type:

<?php
switch (1) {
  case 0:
    echo 0;
    break;
  case 1: // never reached because "a" is already matched with 0
    echo 1;
    break;
}

Upvotes: 1

Ruslan Abuzant
Ruslan Abuzant

Reputation: 631

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

Upvotes: 2

Related Questions