PHP - Get key name of array value

ID : 20200

viewed : 14

Tags : phparraysarray-keyphp

Top 5 Answer for PHP - Get key name of array value

vote vote

97

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

vote vote

81

key($arr); 

will return the key value for the current array element

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

vote vote

76

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

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

See PHP manual

vote vote

60

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

58

Here is another option

$array = [1=>'one', 2=>'two', 3=>'there']; $array = array_flip($array); echo $array['one'];  

Top 3 video Explaining PHP - Get key name of array value

Related QUESTION?