SoLoGHoST
SoLoGHoST

Reputation: 2689

How to get the position of a key within an array

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.

Upvotes: 48

Views: 71611

Answers (4)

hakre
hakre

Reputation: 197624

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.

Upvotes: 10

pho
pho

Reputation: 25489

$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

Upvotes: 2

Sajid
Sajid

Reputation: 4421

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

Upvotes: -3

zerkms
zerkms

Reputation: 254886

$i = array_search('blah', array_keys($array));

Upvotes: 114

Related Questions