php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77584 switch case problem
Submitted: 2019-02-08 08:03 UTC Modified: 2019-02-08 18:11 UTC
From: giolaza at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.2Git-2019-02-08 (Git) OS: ubuntu
Private report: No CVE-ID: None
 [2019-02-08 08:03 UTC] giolaza at gmail dot com
Description:
------------
wrong case using when I am using in_array in empty var;
if var is not empty, for example - $var=0 all works right.

Test script:
---------------
$array=['users','documents','timePunch','vacation','requests'];

$var=1;
$var='';
var_dump($var);
echo PHP_EOL;
switch($var){
	case (in_array($var,$array)):
		echo 'CASE IS TRUE';
		break;
	default:
		echo 'CASE IS DEFAULT';
		break;
}
echo PHP_EOL;
var_dump(in_array($var,$array));



Expected result:
----------------
string(0) ""

CASE IS DEFAULT
bool(false)


Actual result:
--------------
string(0) ""

CASE IS TRUE
bool(false)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-02-08 08:04 UTC] giolaza at gmail dot com
forgot write comment //$var=1;
 [2019-02-08 09:27 UTC] sjon at hortensius dot net
This is not unexpected - but you are obfuscating your code through the switch{}

Since $var='' and you have a case (in_array($var,$array)) you are basically testing whether '' == false (result of in_array($var,$array) ), which it is:

var_dump(''==false) returns true. If you want to test multiple cases in this construct you should use switch(true) - see https://3v4l.org/6B2r8
 [2019-02-08 09:37 UTC] giolaza at gmail dot com
-Status: Open +Status: Closed
 [2019-02-08 09:37 UTC] giolaza at gmail dot com
Thanks for answer
 [2019-02-08 18:11 UTC] requinix@php.net
-Status: Closed +Status: Not a bug
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun May 05 23:01:30 2024 UTC