I want to get the value of the KEY of an associative PHP array at a specific entry. Specifically, I know the KEY I need is the key to the second entry in the array.
Example:
$array = array('customer' => 'Joe', 'phone' => '555-555-5555');
What I'm building is super-dynamic, so I do NOT know the second entry will be 'phone'. Is there an easy way to grab it?
In short, (I know it doesn't work, but...) I'm looking for something functionally equivalent to: key($array[1]);
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key. Save this answer.
Code Inspection: Duplicate array keysReports duplicate keys in array declarations. If multiple elements in the array declaration use the same key, only the last one will be used, and all others will be overwritten.
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.
How do I find the first key of an array? Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.
array_keys produces a numerical array of an array's keys.
$keys = array_keys($array); $key = $keys[1];
If you're using PHP 5.4 or above, you can use a short-hand notation:
$key = array_keys($array)[1];
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