How to get keys from an associative array in PHP

One of PHP’s most powerful features are arrays and the multitude of functions available to interact with and manipulate them. Arrays can be indexed by integers as well as string, known as an associative array. Instead of looping through the array with foreach and assigning the key to another array, you can easily use array_keys() to grab the keys from the array, regardless if it’s associative or not:

$array = array(
	'one'   => 'This is the first',
	'two'   => 'This is the second',
	'three' => 'This is the third',
	'four'  => 'This is the fourth',
	'five'  => 'This is the fifth',


$array_keys = array_keys($array

If you were to print_r($array_keys) you would see something like this:

Array
(
	[0] => one
	[1] => two
	[2] => three
	[3] => four
	[4] => five
)

Using array_keys() is the equivalent of doing something like this:

$array_keys = array

foreach ($array as $key => $value)
{
	$array_keys[] = $key
}

Depending on the circumstances, I will still do it that way from time to time, especially in situations where I have other data manipulation going on and would already be looping through the data. An interesting observation is that when I compared array_keys() against the foreach() over 1,000,000 iterations, they both ran in roughly the same amount of time with no clear winner. The shorter syntax is obviously an advantage and if I had to guess, PHP is probably just performing a foreach() loop internally when calling array_keys().

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.