I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName']
so that I am able to loop through array_keys($arr)
and return the key string 'firstStringName'
by its index. How can I do that?
array_search()
is the feature that accomplishes this:
array_search
— Searches the array for a given value and returns the first corresponding key if successful
If you have a value and want to find the key, use array_search()
like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key
will now contain the key for the value 'a'
(that is, 'first'
).