Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 541
SoLoGHoST Avatar asked Sep 18 '11 06:09

SoLoGHoST


People also ask

How do you find the position of an object in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do you access a key inside an array?

If you want to access the key of an array in a foreach loop, you use the following syntax: foreach ($array as $key => $value) { ... }

How do you find the key and value of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

What is a position in an array called?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


1 Answers

$i = array_search('blah', array_keys($array)); 
like image 85
zerkms Avatar answered Oct 05 '22 01:10

zerkms