Bug #70486 [Opn->Nab]: in_array/array_search returns false-positive
| From: | requinix@php.net | Date: | Mon, 14 Sep 2015 07:10:41 +0000 |
| Subject: | Bug #70486 [Opn->Nab]: in_array/array_search returns false-positive | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-195991@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=70486&edit=1
ID: 70486
Updated by: requinix@php.net
Reported by: david at davidsteinsland dot net
Summary: in_array/array_search returns false-positive
-Status: Open
+Status: Not a bug
Type: Bug
Package: Arrays related
PHP Version: 5.6.13
Block user comment: N
Private report: N
New Comment:
> 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.
Previous Comments:
------------------------------------------------------------------------
[2015-09-14 06:38:27] david at davidsteinsland dot net
Description:
------------
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:
---------------
<?php
$data = ['str', 'str2', 0];
var_dump(in_array('notHere', $data));
var_dump(array_search('notHere', $data));
Expected result:
----------------
bool(false)
bool(false)
Actual result:
--------------
bool(true)
int(2)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=70486&edit=1