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.
$i = array_search('blah', array_keys($array));
If you know the key exists:
PHP 5.4 (Demo):
$keys = array_flip(array_keys($array)); echo $keys['blah'];
If you don’t know the key exists, you can check with
$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.
$keys=array_keys($array); will give you an array containing the keys of
array_search('blah', $keys); will give you the index of
$keys and therefore,
array_search (doc). Namely, `$index = array_search(‘blah’, $array)