Vitaly Dyatlov
Vitaly Dyatlov

Reputation: 1872

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?

Upvotes: 4

Views: 220

Answers (2)

mishu
mishu

Reputation: 5397

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)

Upvotes: 2

Jon
Jon

Reputation: 437834

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.

Upvotes: 7

Related Questions