php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71905 invalid switch case is returning valid
Submitted: 2016-03-26 14:28 UTC Modified: 2016-03-26 16:19 UTC
From: pat at breakfree dot com Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 5.5.33 OS: Ubuntu 14.04
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: pat at breakfree dot com
New email:
PHP Version: OS:

 

 [2016-03-26 14:28 UTC] pat at breakfree dot com
Description:
------------
A false switch case is returning valid.
Perhaps related to key index returned from stat()?


PHP 5.5.9-1ubuntu4.14 (cli) (built: Oct 28 2015 01:34:46) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies



Test script:
---------------
<?php
$s = stat('/tmp');
/*
 * I was interested in data from a few keys. However I found the 0/dev key is always resulting as a true case. 
 */
$x = 0;
foreach($s as $k => $v) {
	switch($k) {
		case 'this_does_not_exist_and_should_never_occur':
			echo 'Yet this case occurs: ' . $k . ', ' . $v . "\n";
			$x++;
			break;
		default:
			break;
	}
}
echo "x=" . $x . "\n";
?>

Expected result:
----------------
x=0


Actual result:
--------------
Yet this case occurs: 0, 64769
x=1




Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-03-26 14:45 UTC] bwoebi@php.net
-Status: Open +Status: Not a bug
 [2016-03-26 14:45 UTC] bwoebi@php.net
Switch cases are using weak comparisons and as 0 == "string" results in true, this is expected behavior. Add an if (is_int($k)) continue; to solve your specific problem here.
 [2016-03-26 16:19 UTC] pat at breakfree dot com
Ah - I was unaware of how fragile a weak comparison is.
I totally understand now.  Thank you for the education.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 01:01:30 2024 UTC