Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get key name of array value

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?

like image 589
headacheCoder Avatar asked Sep 25 '22 15:09

headacheCoder


People also ask

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

What is key in PHP 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 .

Which array has named keys?

Associative arrays are arrays that use named keys that you assign to them.

How get the key of an object in PHP?

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);


2 Answers

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').

like image 425
zrvan Avatar answered Oct 14 '22 05:10

zrvan


key($arr);

will return the key value for the current array element

http://uk.php.net/manual/en/function.key.php

like image 79
Mark Baker Avatar answered Oct 14 '22 07:10

Mark Baker