Thursday, December 25, 2025
HomeLanguagesHow to loop through an associative array and get the key in...

How to loop through an associative array and get the key in PHP?

Associative Array: Associative arrays are used to store key-value pairs. For example, to store the marks of the different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. In associative array, the key-value pairs are associated with => symbol.

Method 1: In this method, traverse the entire associative array using foreach loop and display the key elements.
Program: Program to loop through associative array and print keys.




<?php
// Loop through associative array and get
// the key of associative array
  
// Associative array
$person_weight = array(
    "Rajnish" => 58, 
    "Sanjeev" => 55, 
    "Ravi" => 60, 
    "Yash" => 60,
    "Suraj" => 48
); 
  
// Use for-each loop and display the
// key of associative array
foreach($person_weight as $key => $value) { 
    echo "Key: " . $key . "\n"; 
}
  
?>


Output:

Key: Rajnish
Key: Sanjeev
Key: Ravi
Key: Yash
Key: Suraj

Method 2: Using array_keys() function: The array_keys() is an inbuilt function in PHP which is used to return either all the keys of array or the subset of the keys.

Syntax:

array array_keys( $input_array, $search_value, $strict )

Program: Below program illustrate the use of array_keys() function to accessing the keys of associative array.




<?php
// Use array_keys() function to display
// the key of associative array
  
// Associative array
$assoc_array = array(
    "Geeks" => 30,
    "for" => 20,
    "neveropen" => 10
); 
  
// Using array_keys() function
$key = array_keys($assoc_array);
  
// Calculate the size of array
$size = sizeof($key);
  
// Using loop to access keys
for( $i = 0; $i < $size; $i++) {
    echo "key: ${key[$i]}\n";
}
  
?>


Output:

key: Geeks
key: for
key: neveropen
RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6825 POSTS0 COMMENTS
Nicole Veronica
11960 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6959 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6912 POSTS0 COMMENTS
Umr Jansen
6893 POSTS0 COMMENTS