php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #29155 switch odd behaviour with mixed int/string variables
Submitted: 2004-07-14 16:46 UTC Modified: 2004-07-15 15:30 UTC
From: phpbug at bart dot w-wa dot pl Assigned:
Status: Not a bug Package: Variables related
PHP Version: 4.3.7 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: phpbug at bart dot w-wa dot pl
New email:
PHP Version: OS:

 

 [2004-07-14 16:46 UTC] phpbug at bart dot w-wa dot pl
Description:
------------
Due to FU typecasting switch produces unexpected results when one of the cases is string, but variable passed to switch is int. 
 

Reproduce code:
---------------
$x = 0;
switch($x) {
case 'something': echo 'something'; break;
case 0:           echo 'zero'; break;
default:          echo 'something else';
};


Expected result:
----------------
zero

Actual result:
--------------
something

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-07-14 16:49 UTC] derick@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

.
 [2004-07-14 22:48 UTC] no at spam dot forme
you test one integer 0 against a string, which causes php to cast your string into an integer, which results in 0 for the string  'something'. thus, the first case comparison looks like 0 == 'something' <=> 0 == 0 <=> true, the program prints 'something' and breaks the switch. Your result is the expected result. I think this should be more explicitly empathized in the php manual.
 [2004-07-15 15:30 UTC] phpbug at bart dot w-wa dot pl
I am aware _why_ this happens, but still I do belive it's a flaw. Perhaps a flaw in design, not the code itself. This odd behavior is unique to PHP. In other languages, where == is used both for int and string comparison 0 != 'something' (eg. JavaScript). In Perl 0 == 'something' only becouse == is an operator for _numeric_ comparison, while strings are compared with eq operator. 

BTW, the example "works" other way around too:
$x = 'something';
switch($x) {
case 0: echo 'wrong'; break;
case 'something': echo 'ok'; break;
};
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed May 01 02:01:31 2024 UTC