Problem with SWITCH statement in PHP

This is my sample code:

<?php $t = 0; switch( $t ) { case 'add': echo 'add'; break; default: echo 'default'; break; } echo "<br/>"; echo system('php --version'); 

This is the result (tested on codepad.org - the result is the same):

 add PHP 5.3.6-13ubuntu3.6 with Suhosin-Patch (cli) (built: Feb 11 2012 03:26:01) Copyright (c) 1997-2011 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies 

What is wrong here?

+4
source share
2 answers

Your variable $t has an integer value of 0 . Using the switch you tell PHP to compare it first with the value of 'add' (string). PHP does this by converting 'add' to an integer and due to the conversion rules, the result is 0 .

As a result, the first branch is taken - which may be surprising, but it was also expected.

You will see the expected behavior if you did

 $t = "0"; 

Now both $t and 'add' are strings, so magic conversion does not occur, and of course they compare unequal ones.

+7
source

because you are comparing int with a string .. if you force 'add' to int, then there will be 0 .. "fix" your switch statement, which you can replace

 switch( $t ) 

to

 switch( $t . '' ) 

thus, telling the server it should use the string value t (or any other way to do this)

+2
source

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


All Articles