47

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.

SoLoGHoST
  • 2,673
  • 7
  • 30
  • 51

4 Answers4

113
$i = array_search('blah', array_keys($array));
zerkms
  • 249,484
  • 69
  • 436
  • 539
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.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Yeah, I know for a fact that the key will always exist! In that case, would this be faster than using `array_search`? – SoLoGHoST Sep 18 '11 at 08:00
  • 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`. – hakre Sep 18 '11 at 08:02
  • 1
    I like the idea, but array_search is actually faster according to my tests (at least in PHP 5.3). – Thomas Sahlin Jan 29 '15 at 09:11
  • 1
    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) – Déjà vu Jul 09 '16 at 09:00
0

$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

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
-3

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

Sajid
  • 4,381
  • 20
  • 14
  • 3
    No ! Like the doc says: Searches the array for a given **value**, not a **key** as the user asked. – Erdal G. Nov 05 '14 at 13:34