Home » Php » php – How to get the position of a key within an array

php – How to get the position of a key within an array

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:
$i = array_search('blah', array_keys($array));

Answer:

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.

Answer:

$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

Answer:

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