If I have:
$array = array( 'one' =>'value', 'two' => 'value2' );
how do I get the string one
back from $array[1]
?
Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.
Answer: Use the PHP array_values() function You can use the PHP array_values() function to get all the values of an associative array.
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' ).
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With