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?
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
Return Values ¶ The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null .
Associative arrays are arrays that use named keys that you assign to them.
You can cast the object to an array like this: $myarray = (array)$myobject; And then, for an array that has only a single value, this should fetch the key for that value. $value = key($myarray);
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 value 'a'
(that is, 'first'
).
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With