Bug #76994 [Com]: in_array/array_search unexpected result
| From: | sjon at hortensius dot net | Date: | Wed, 10 Oct 2018 14:33:50 +0000 |
| Subject: | Bug #76994 [Com]: in_array/array_search unexpected result | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-217506@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=76994&edit=1
ID: 76994
Comment by: sjon at hortensius dot net
Reported by: luigi dot gualtieri at gmail dot com
Summary: in_array/array_search unexpected result
Status: Open
Type: Bug
Package: Arrays related
Operating System: WIN + LINUX
PHP Version: 7.0.32
Block user comment: N
Private report: N
New Comment:
this is not a bug, see for example var_dump(45 == '45x');
to work-around this, use the third parameter of both functions: $strict=true
Previous Comments:
------------------------------------------------------------------------
[2018-10-10 14:32:36] spam2 at rhsoft dot net
because you use it wrong
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
http://php.net/manual/en/language.types.type-juggling.php
________________
[harry@rh:/downloads]$ php test.php
bool(true)
bool(false)
________________
[harry@rh:/downloads]$ cat test.php
<?php
$needle = '45x';
$haystack = ["23", 34, 45, "abc"];
$result = in_array($needle, $haystack);
var_dump($result);
$result = in_array($needle, $haystack, TRUE);
var_dump($result);
------------------------------------------------------------------------
[2018-10-10 14:28:11] luigi dot gualtieri at gmail dot com
Description:
------------
This is the scenario:
- the needle is a string that starts with a numeric content (eg: "45x")
- haystack contains a numeric item that match the numeric part of the needle (eg: ["23",
34, 45, "abc"]
in_array function returns true and array_search function returns int(2).
Test script:
---------------
<?php
$needle = '45x';
$haystack = ["23", 34, 45, "abc"];
//$test = 'g\'"';
//$test_array = ["g"];
$result = in_array($needle, $haystack );
var_dump($result);
$result = array_search($needle, $haystack );
var_dump($result);
Expected result:
----------------
functions have to return false
Actual result:
--------------
in_array: bool(true)
array_search: int(2)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=76994&edit=1