PHP

Associative Array Looping


 

The each() function is an older method for iterating through associative arrays in PHP. It's not commonly used in modern PHP, and its use is discouraged. Instead, you are encouraged to use foreach loops for better readability and compatibility.

 

Looping using each():

<?php
$assocArray = array(
    "name" => "Raj",
    "age" => 22,
    "city" => "New Delhi"
);

// Reset the array pointer to the beginning
reset($assocArray);

// Loop through the associative array using each()
while ($element = each($assocArray))
{
    $key = $element['key'];
    $value = $element['value'];
    echo "Key: $key, Value: $value<br>";
}
?>

 

Explanation:

 

1. reset($assocArray) is used to set the internal array pointer to the first element of the associative array.
2. The while loop uses each($assocArray) to retrieve the current key-value pair in each iteration.
3. The array returned by each() has keys 'key' and 'value' representing the current key and value.
 

 

Looping using foreach():

 

<?php
    $myAssocArray = array(
        "name" => "Raj",
        "age" => 22,
        "city" => "Kolkata"
    );

    // Loop through the associative array using foreach
    foreach ($myAssocArray as $key => $value) {
        echo "Key: $key, Value: $value<br>";
    }
?>

 

Explanation:

 

1. foreach ($assocArray as $key => $value) iterates through each key-value pair in the associative array.
2. $key represents the current key, and $value represents the current value.
3. Inside the loop, echo "Key: $key, Value: $value<br>"; prints the current key and value of the array.