Looping an Array Using each() and foreach() in PHP

Looping through arrays is one of the most common operations in PHP.
Two classic ways to iterate over arrays are:

  • each() (older, now deprecated)
  • foreach() (recommended and widely used)

Let’s understand both with clear examples.


1. Looping Using each() Function

Note: each() was deprecated in PHP 7.2 and removed in PHP 8.
It is explained here only for legacy code understanding.

The each() function returns the current key–value pair from an array and moves the internal pointer forward.

Example (Works only in PHP 7 and older versions):

$fruits = ["Apple", "Banana", "Cherry"];

reset($fruits); // Move pointer to first element

while ($item = each($fruits)) {
    echo "Key: ".$item['key']." - Value: ".$item['value']."<br>";
}

Output

Key: 0 - Value: Apple
Key: 1 - Value: Banana
Key: 2 - Value: Cherry

2. Looping Using foreach() Loop (Modern & Recommended)

foreach() is the most efficient and easiest way to loop through arrays in PHP.


a) Looping Indexed Arrays

$colors = ["Red", "Green", "Blue"];

foreach ($colors as $color) {
    echo $color . "<br>";
}

b) Looping Associative Arrays

$user = [
    "name" => "Sagar",
    "role" => "Developer",
    "age" => 25
];

foreach ($user as $key => $value) {
    echo "$key : $value <br>";
}

c) Nested Array Looping

$students = [
    ["Amit", 85],
    ["Rohit", 90]
];

foreach ($students as $student) {
    echo "Name: ".$student[0]." - Marks: ".$student[1]."<br>";
}

3. Why foreach() Is Better?

Featureeach()foreach()
DeprecatedYesNo
Works in PHP 8✔️
Easy to read✔️
SpeedSlowFast
RecommendedNoYes

Conclusion

  • Use foreach() for all modern PHP projects.
  • Learn each() only for reading or maintaining legacy code.

foreach() is cleaner, simpler, and fully supported across PHP versions.


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *