|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70486 in_array/array_search returns false-positive
Submitted: 2015-09-14 06:38 UTC Modified: 2015-09-14 07:10 UTC
From: david at davidsteinsland dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.6.13 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: david at davidsteinsland dot net
New email:
PHP Version: OS:


 [2015-09-14 06:38 UTC] david at davidsteinsland dot net
The following test script is tested on PHP 5.4.43 (FreeBSD), PHP 5.5.20 (CentOS), PHP 5.6.10 (OSX).

All tests say that "notHere" is in the array, and index 2.

Before you say that the third parameter, "strict", will fix this. Consider:

var_dump((int)'notHere' === 0);
var_dump('notHere' === (string)0);

I believe that it is the first casting that is being done internally in PHP? Would it not make more sense to cast it the other way around, as in no. 2?

They look similar, but are completely different.

In the first example I am searching for a string, "notHere". It's being casted to a integer (completely different value and type now), so it matches integer 0.

In the second example I am still searching for a string, but now instead of casting the needle, the tested value is casted. The result of this comparison is false.

Test script:

$data = ['str', 'str2', 0];
var_dump(in_array('notHere', $data));
var_dump(array_search('notHere', $data));

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-09-14 07:10 UTC]
-Status: Open +Status: Not a bug
 [2015-09-14 07:10 UTC]
> Would it not make more sense to cast it the other way around, as in no. 2?
It could, in some situations, yes. The fact is that whichever way PHP worked, somebody would be left at a disadvantage because it doesn't do what they want. Personally, I think of how the majority of input to PHP is in the form of strings (URLs, form input, cookies, some database drivers...) so casting string->number makes more sense more often.

But this really isn't the place for a discussion. If you want more information about why PHP works the way it does (and comments to how changing it would be a massive BC break) then I suggest the internals mailing list.
 [2019-06-28 18:48 UTC] allenmccabe at gmail dot com
The root of the issue is not in_array(), but rather type-casting of the string ( "The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)."
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Thu Jun 30 22:03:33 2022 UTC