How to Get All Keys of an Associative Array in PHP?
Last Updated :
17 Apr, 2024
Given an Associative array, the task is to get all the keys of the associative array in PHP. There are two approaches to get all keys from the associative array, these are – using array_keys(), and foreach loop. In this article, we will explore these approaches with examples.
Approach 1: Using the array_keys() Function
The array_keys() function returns an array containing the keys of an associative array.
PHP
<?php
$subjects = array(
"Maths" => 95,
"Physics" => 90,
"Chemistry" => 96,
"English" => 93,
"Computer" => 98
);
$keys = array_keys($subjects);
print_r($keys);
?>
OutputArray
(
[0] => Maths
[1] => Physics
[2] => Chemistry
[3] => English
[4] => Computer
)
Approach 2: Using a foreach Loop
You can use a foreach loop to iterate over the associative array and extract the keys of array.
PHP
<?php
$subjects = array(
"Maths" => 95,
"Physics" => 90,
"Chemistry" => 96,
"English" => 93,
"Computer" => 98
);
$keys = [];
foreach ($subjects as $key => $value) {
$keys[] = $key;
}
print_r($keys);
?>
OutputArray
(
[0] => Maths
[1] => Physics
[2] => Chemistry
[3] => English
[4] => Computer
)
Share your thoughts in the comments
Please Login to comment...