note 122377 deleted from function.array-search by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 20:45:34 +0000 |
| Subject: | note 122377 deleted from function.array-search by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217961@lists.php.net to get a copy of this message | ||
Note Submitter: Xriuk
----
Be careful when search for indexes from array_keys() if you have a mixed associative array it will
return both strings and integers resulting in comparison errors
<?php
// This syntax is allowed by PHP
$arr = array(
"nice",
"car" => "fast",
"none"
);
// Print the keys
var_dump(array_keys($arr));
/* The above prints this, as you can see we have mixed keys
array(3) {
[0]=>
int(0)
[1]=>
string(3) "car"
[2]=>
int(1)
}
*/
// Search for the index "car"
var_dump(array_search("car", array_keys($arr))); // Prints "int(0)" which is
WRONG
?>
This happens because PHP, when comparing strings and integers, casts strings TO integers and this
results in most of the cases in string becoming 0, so that's why when array_search() compares
the first index (0) with the key "car" it gets true because apparently ("car" ==
0) IS TRUE.
Setting array_search() to strict mode won't solve the problem because then
array_search("0", array_keys($arr)) would return false even if an element with index 0
exists.
So my solution just converts all indexes from array_keys() to strings and then compares them
correctly:
<?php
var_dump(array_search("car", array_map("strval", array_keys($arr)))); // Prints
"int(1)" which is CORRECT
?>