0
0
PhpHow-ToBeginner · 3 min read

How to Iterate Over Array in PHP: Simple Syntax and Examples

In PHP, you can iterate over an array using the foreach loop, which goes through each element one by one. The syntax is foreach ($array as $value) to access values or foreach ($array as $key => $value) to access keys and values.
📐

Syntax

The foreach loop is the easiest way to iterate over arrays in PHP. It has two common forms:

  • foreach ($array as $value): Loops through each value in the array.
  • foreach ($array as $key => $value): Loops through each key and value pair.

This loop automatically moves through the array without needing to manage indexes.

php
foreach ($array as $value) {
    // code using $value
}

foreach ($array as $key => $value) {
    // code using $key and $value
}
💻

Example

This example shows how to use foreach to print all values and keys with values from an array.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

// Iterate values only
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

echo "---\n";

// Iterate keys and values
foreach ($fruits as $index => $fruit) {
    echo "Index $index: $fruit\n";
}
?>
Output
apple banana cherry --- Index 0: apple Index 1: banana Index 2: cherry
⚠️

Common Pitfalls

Common mistakes when iterating arrays in PHP include:

  • Using for loops without knowing the array length, which can cause errors.
  • Modifying the array inside the foreach loop, which can lead to unexpected behavior.
  • Confusing keys and values when using foreach with as $value only.

Always use foreach for simple and safe iteration over arrays.

php
<?php
// Wrong: Using for loop without count
$colors = ['red', 'green', 'blue'];
for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . "\n"; // Safe iteration
}

// Right: Use foreach
foreach ($colors as $color) {
    echo $color . "\n";
}
Output
red green blue red green blue
📊

Quick Reference

Remember these tips when iterating arrays in PHP:

  • Use foreach for clean and readable loops.
  • Access keys and values with foreach ($array as $key => $value).
  • Do not change the array inside the loop unless you know what you are doing.
  • Use count() if you need the array length.

Key Takeaways

Use foreach to easily loop through all elements of an array in PHP.
Access both keys and values by using foreach ($array as $key => $value).
Avoid modifying the array inside a foreach loop to prevent bugs.
Do not use for loops without checking array length to avoid errors.
Remember foreach works with any array type, including associative arrays.