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?

share|improve this question
Can you elaborate with a use case of what you're trying to achieve? – nikc.org Jan 4 '12 at 15:34

closed as not a real question by nikc.org, Jakub, Neal, hakre, Gordon Jan 4 '12 at 15:45

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

7 Answers

use array_keys() to get an array of all the unique keys.

Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].

http://php.net/manual/en/function.array-keys.php

share|improve this answer
key($arr);

will return the key value for the current array element

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

share|improve this answer

If the name's dynamic, then you must have something like

$arr[$key]

which'd mean that $key contains the value of the key.

You can use array_keys() to get ALL the keys of an array, e.g.

$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);

would give you

$x = array(0 => 'a', 1 => 'c');
share|improve this answer

Yes you can infact php is one of the few languages who provide such support..

foreach($arr as $key=>$value)
{

}
share|improve this answer

If you have a value and want to find the key, use array_search() php.net. Use it 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').

share|improve this answer

If i understand correctly, can't you simply use:

foreach($arr as $key=>$value){
echo $key;
}

See PHP manual

share|improve this answer
You'd just be displaying the array element values, not the array keys.... foreach($arr as $key => $value){ – Mark Baker Jan 4 '12 at 15:39
Edited. Thanks Mark! – Ryan Jan 4 '12 at 15:40

Check the documentation for array_keys() function

array_keys Function

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.