I’m working with an associative array and need to determine the numeric location of a key. I could manually cycle through the array to find it, but is there a more efficient technique built into PHP?
$a = array( 'blue' => 'nice', 'car' => 'fast', 'number' => 'none' ); // echo (find numeric index of $a['car']); // output: 1
Asked by n00b
Answered by Fosco
$blue_keys = array_search("blue", array_keys($a));
Answered by quantumSoup
While Fosco’s response is correct, there is an exception to be made in this case: mixed arrays. Assume I have the following array:
$a = array( "nice", "car" => "fast", "none" );
Now, PHP accepts this syntax, but it has one flaw: when I run Fosco’s code, I receive 0 instead of 1, which is incorrect for me, but why does this happen? Because PHP turns strings to numbers when comparing strings to integers (which I think is foolish), when array search() searches for the index, it stops at the first one because (“car” == 0) appears to be true. Setting array_search() to strict mode won’t solve the problem because then array_search(“0”, array_keys($a)) 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:
echo array_search("car", array_map("strval", array_keys($a)));
The output is 1, which is correct.
EDIT: As Shaun pointed out in the comments below, the same thing holds true for the index value if you’re looking for an int index that looks like this:
$a = array( "foo" => "bar", "nice", "car" => "fast", "none" ); $ind = 0; echo array_search($ind, array_map("strval", array_keys($a)));
Because you’ll always get 0, which is incorrect, you need cast the index (if you’re using a variable) to a string like this:
$ind = 0; echo array_search((string)$ind, array_map("strval", array_keys($a)));
Answered by Xriuk
$a = array( 'blue' => 'nice', 'car' => 'fast', 'number' => 'none' ); var_dump(array_search('car', array_keys($a))); var_dump(array_search('blue', array_keys($a))); var_dump(array_search('number', array_keys($a)));
Answered by Asterión
The approach with array search would be quite heavy, and straight search is unneeded in this case.
A far superior solution would be:
$keyIndexOfWhichYouAreTryingToFind = 'c'; $array = [ 'a' => 'b', 'c' => 'd' ]; $index = array_flip(array_keys($array))[$keyIndexOfWhichYouAreTryingToFind];
On large arrays, this type of search might perform considerably better. The difficulty, which would be O(n)=1 instead of O(n)=n, is the cause (in worst of the possible variants). So, instead of 1000000 iterations, for an array with 1000000 elements, it would take 1 iteration.
Answered by nojitsi
Post is based on https://stackoverflow.com/questions/3365766/php-get-numeric-index-of-associative-array