How to use for-each loop In PHP
In this method, traverse the entire associative array using each loop and display the key elements.
Example: Program to loop through the 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
How to loop through an associative array and get the key in PHP?
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.
here are some common approaches:
Table of Content
- Using for-each loop
- Using array_keys() function
- Using array_walk function