A foreach loop helps you go through each item in an array easily. It saves time and makes your code simple.
0
0
Foreach loop for arrays in PHP
Introduction
When you want to print all items in a shopping list.
When you need to check every student's grade in a class.
When you want to add a prefix to every word in a list.
When you want to count or process each element in a collection.
Syntax
PHP
<?php $array = ["apple", "banana", "cherry"]; foreach ($array as $item) { // use $item here } ?>
The $item variable holds the current element in the loop.
You can also get the key (index) with foreach ($array as $key => $value).
Examples
This prints each fruit name on a new line.
PHP
<?php $fruits = ["apple", "banana", "cherry"]; foreach ($fruits as $fruit) { echo $fruit . "\n"; } ?>
If the array is empty, the loop does not run at all.
PHP
<?php $emptyArray = []; foreach ($emptyArray as $item) { echo $item; } // Nothing happens because array is empty ?>
Works fine even if there is only one element.
PHP
<?php $numbers = [10]; foreach ($numbers as $number) { echo $number . "\n"; } ?>
Shows how to get both index and value.
PHP
<?php $colors = ["red", "green", "blue"]; foreach ($colors as $index => $color) { echo "Color at index $index is $color\n"; } ?>
Sample Program
This program shows the array before looping and then prints each item using foreach.
PHP
<?php $shoppingList = ["milk", "bread", "eggs"]; echo "Before loop:\n"; print_r($shoppingList); echo "\nUsing foreach loop to print items:\n"; foreach ($shoppingList as $item) { echo "Item: $item\n"; } ?>
OutputSuccess
Important Notes
Time complexity is O(n) because it visits each element once.
Space complexity is O(1) extra space since it uses the existing array.
Common mistake: modifying the array inside the foreach can cause unexpected results.
Use foreach when you want to read or process each element simply. Use for loop if you need index control or to modify array size.
Summary
Foreach loops make it easy to visit every item in an array.
You can get just the value or both key and value.
It works well even if the array is empty or has one item.