php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76994 in_array/array_search unexpected result
Submitted: 2018-10-10 14:28 UTC Modified: 2018-10-10 14:40 UTC
From: luigi dot gualtieri at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.0.32 OS: WIN + LINUX
Private report: No CVE-ID: None
 [2018-10-10 14:28 UTC] 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)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-10-10 14:32 UTC] 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:33 UTC] sjon at hortensius dot net
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
 [2018-10-10 14:40 UTC] peehaa@php.net
-Status: Open +Status: Not a bug
 [2018-10-10 14:40 UTC] peehaa@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
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sat Mar 28 19:01:27 2020 UTC