Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue 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 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?

like image 968
Vitaly Dyatlov Avatar asked Jan 18 '23 07:01

Vitaly Dyatlov


2 Answers

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.

like image 120
Jon Avatar answered Jan 20 '23 17:01

Jon


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)

like image 26
mishu Avatar answered Jan 20 '23 17:01

mishu