Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nth key of associative php array [duplicate]

Tags:

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]);

like image 974
jtubre Avatar asked Apr 20 '15 00:04

jtubre


People also ask

What will happen if the key element in associative array is repeated twice?

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.

Can a PHP array have duplicate keys?

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.

How do you print the key in an associative array?

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 you get the first key 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.


1 Answers

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]; 
like image 141
Devon Avatar answered Oct 28 '22 07:10

Devon