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 output (tested on codepad.org - 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?
Your variable $t
has the integer value 0
. With the switch
statement you tell PHP to compare it first with the value 'add'
(a string). PHP does this by converting 'add'
to an integer, and due to the rules of the conversion the result turns out to be 0
.
As a result, the first branch is taken -- which may be surprising, but it's also expected.
You would see the expected behavior if you did
$t = "0";
Now, both $t
and 'add'
are strings so there is no magic conversion going on and of course they compare unequal.
that's because you are comparing an int with an string.. if you force the conversion of 'add' to int it will be 0.. to "fix" your switch statement you can replace
switch( $t )
to
switch( $t . '' )
this way telling the server he should use the string value of t (or any other way to achieve this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With