How to get the position of a key within an array
Asked Answered
N

4

48

Ok, so I need to grab the position of 'blah' within this array (position will not always be the same). For example:

$array = (
    'a' => $some_content,
    'b' => $more_content,
    'c' => array($content),
    'blah' => array($stuff),
    'd' => $info,
    'e' => $more_info,
);

So, I would like to be able to return the number of where the 'blah' key is located at within the array. In this scenario, it should return 3. How can I do this quickly? And without affecting the $array array at all.

Nocturn answered 18/9, 2011 at 6:15 Comment(0)
D
114
$i = array_search('blah', array_keys($array));
Derek answered 18/9, 2011 at 6:16 Comment(0)
H
10

If you know the key exists:

PHP 5.4 (Demo):

echo array_flip(array_keys($array))['blah'];

PHP 5.3:

$keys = array_flip(array_keys($array));
echo $keys['blah'];

If you don't know the key exists, you can check with isset:

$keys = array_flip(array_keys($array));
echo isset($keys['blah']) ? $keys['blah'] : 'not found' ;

This is merely like array_search but makes use of the map that exists already inside any array. I can't say if it's really better than array_search, this might depend on the scenario, so just another alternative.

Houck answered 18/9, 2011 at 7:40 Comment(4)
Yeah, I know for a fact that the key will always exist! In that case, would this be faster than using array_search?Nocturn
Let me answer this way: As long as array_flip is faster than array_search, it is :). The key lookup itself is faster than array_search.Houck
I like the idea, but array_search is actually faster according to my tests (at least in PHP 5.3).Vendue
Depends if you need many lookups in the same array... If you search for - say - all keys, array_search is O(n²), with array_flip that would be O(n). If you need a couple of lookups go for search. (for both solutions you would of course save the intermediate array in another variable in case you need multiple lookups, sake of perf)Old
D
1

$keys=array_keys($array); will give you an array containing the keys of $array

So, array_search('blah', $keys); will give you the index of blah in $keys and therefore, $array

December answered 18/9, 2011 at 6:24 Comment(0)
E
-3

User array_search (doc). Namely, `$index = array_search('blah', $array)

Expedite answered 18/9, 2011 at 6:16 Comment(1)
No ! Like the doc says: Searches the array for a given value, not a key as the user asked.Merkley

© 2022 - 2024 — McMap. All rights reserved.