Please explain why the PHP switch case always executes register 0 in this code

Can someone explain why case "a" is never reached in the lower 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; } 
+5
source share
4 answers

PHP, such as JavaScript or Perl, is a language that does not have a language and will try to guess what you want to do. In this case, he changed your string to the nearest integer that he could find, which is zero. In other words, "a" == 0 is a true expression in PHP.

More information on this topic can be found in the PHP documentation . I suggest you enter a value in a switch or replace it with an if / elseif / else .

+3
source

You cannot use mixed cases in a switch statement, as PHP will interpret the meaning of what you mean.

Under the conditions of a layman, he will try to find the "value" a ", which is not defined by the processor, and, therefore, in this case is 0.

The same goes 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 on PHP.net.

+2
source

The variable type used for case () must be of the same type as 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; } 
+1
source

The reason for this is that switch uses free == comparison

That said:

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

Quite a lot more will be evaluated as false. (except "a" == "a" )

So, if you need to match both strings and integers, you just need to convert to a string for comparison.

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

Source: https://habr.com/ru/post/1262674/


All Articles