php: how to get associative array key from numeric index?
Solution 1:
You don't. Your array doesn't have a key [1]
. You could:
-
Make a new array, which contains the keys:
$newArray = array_keys($array); echo $newArray[0];
But the value "one" is at
$newArray[0]
, not[1]
.
A shortcut would be:echo current(array_keys($array));
-
Get the first key of the array:
reset($array); echo key($array);
-
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.
Solution 2:
$array = array( 'one' =>'value', 'two' => 'value2' );
$allKeys = array_keys($array);
echo $allKeys[0];
Which will output:
one
Solution 3:
If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:
echo array_keys($array)[$i];
Solution 4:
Or if you need it in a loop
foreach ($array as $key => $value)
{
echo $key . ':' . $value . "\n";
}
//Result:
//one:value
//two:value2