Search code examples
phparraysarray-key

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?


Solution

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