php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77585 in_array wrong answer
Submitted: 2019-02-08 08:12 UTC Modified: 2019-02-08 18:11 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
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:12 UTC] giolaza at gmail dot com
Description:
------------
in array return true if I am checking 0 var

if $var=0;  result is wrong

int(0)
in_array IS TRUE
bool(true)

$var=(int) 1-1; result is wrong;

int(0)
in_array IS TRUE
bool(true)

if $var=1;  result is current


int(1)
in_array IS FALSE
bool(false)


if $var=NULL;  result is current


NULL
in_array IS FALSE
bool(false)


if $var='';  result is current


string(0) ""
in_array IS FALSE
bool(false)


Test script:
---------------
<?php
$array=['users','documents','timePunch','vacation','requests'];
$var=0;
if(in_array($var,$array)){
	echo 'in_array IS TRUE';
}
else{
	echo 'in_array IS FALSE';
}
echo PHP_EOL;
var_dump(in_array($var,$array));

Expected result:
----------------
in_array IS FALSE
bool(false)


Actual result:
--------------
in_array IS TRUE
bool(true)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-02-08 08:22 UTC] giolaza at gmail dot com
maybe. this result is because php tries to make same types during checking

if(intval($array[0])==$var)
because if(0=='string') is true too( 


but I thing this is wrong;
 [2019-02-08 09:32 UTC] spam2 at rhsoft dot net
http://php.net/manual/en/language.types.type-juggling.php
in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

well, in_array without the strict-param was exactly because of such behavior in the last security chistmas calendar

<?php
$array=['users','documents','timePunch','vacation','requests'];
$var=0;
if(in_array($var,$array,TRUE)){
 echo 'in_array IS TRUE';
}
else{
 echo 'in_array IS FALSE';
}
echo PHP_EOL;
var_dump(in_array($var,$array,TRUE));
?>
 [2019-02-08 09:33 UTC] sjon at hortensius dot net
You should checkout https://secure.php.net/manual/en/types.comparisons.php - it shows 0 == "anything"

If you want strict checking, pass the $strict=true parameter to in_array
 [2019-02-08 09:34 UTC] giolaza at gmail dot com
-Status: Open +Status: Closed
 [2019-02-08 09:34 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: Mon May 06 02:01:31 2024 UTC