Signup/Sign In

How to get all the keys of an associative array in PHP?

Answer: Using array_keys() function

We can get all the keys of an associative array using the array_keys() function. It is a built-in PHP function that is used to get all the keys of an array.

The array_keys() function takes the array as its input and returns the array consists of all the keys of the input array.

Example: Getting all the keys of an array

In the given example, we get all the keys from the associative array name $arr using array_keys() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Getting all the keys of an associative array</title>
</head> 
<body>  
	<?php
		$arr = array("James" => "Developer", "Robert" => "Team lead", "Michael" => "HR", "Thomas" => "Developer", "Daniel" => "Writer");
		$newArr = array_keys($arr);
		print_r($newArr);
	?>
</body>  
</html>  


Array ( [0] => James [1] => Robert [2] => Michael [3] => Thomas [4] => Daniel )

Using foreach loop

We can also get all the array keys of an associative array using a foreach loop by specifying some conditions within the for loop, we can iterate through the array and get all the keys present within the given array.

Example: Getting all the keys of associative array

In the given example, we get all the keys of the associative array named $arr using the foreach loop.

<!DOCTYPE html>  
<html> 
<head>
	<title>Getting all the keys of an associative array</title>
</head> 
<body>  
	<?php
		$arr = array("James" => "Developer", "Robert" => "Team lead", "Michael" => "HR", "Thomas" => "Developer", "Daniel" => "Writer");
		foreach($arr as $key => $value){
			echo $key . "<br>";
		}
	?>
</body>  
</html>  


James
Robert
Michael
Thomas
Daniel

Conclusion

In this lesson, we have learned how to get all the keys of the associative array in PHP. We used the built-in array_keys() function that takes the array as its input and returns the array consists of all the keys of that array. We can also get all the keys of an array using the foreach loop.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.