PHP foreach Loop

Introduction

In PHP, loops are used to execute a block of code repeatedly. When working with arrays and objects, one of the most convenient and commonly used loops is the foreach loop.

Unlike other loops such as for or while, the foreach loop is specifically designed to iterate over arrays and objects easily. It removes the need for manual indexing and makes your code cleaner, more readable, and less error-prone.

What is PHP foreach Loop?

The foreach loop in PHP is used to iterate over elements of an array or object. It automatically assigns each value (and optionally the key) to a variable during each iteration.

📖
Important Points:
  • It loops through each element of an array
  • No need to manage index manually
  • Works only with arrays and objects
  • Supports key-value pairs
  • Automatically moves to next element

Syntax

1. foreach with Value Only


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

Note: Used when you only need values.

2. foreach with Key and Value


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

Note: Used when you need both key and value.

Examples:

Example 1: Iterating Array Values


<?php
$game_arr = array('Hockey', 'Cricket', 'Tennis', 'Football');
foreach($game_arr as $game_name) {
   echo $game_name . '<br/>';
}
?>

Output:

Hockey
Cricket
Tennis
Football

Example 2: Iterating with Key and Value


<?php
$game = array('Hockey', 'Cricket', 'Tennis', 'Football');
foreach($game as $key => $game_name) {
   echo $game_name . ' is on array position ' . $key . '<br/>';
}
?>

Output:

Hockey is on array position 0
Cricket is on array position 1
Tennis is on array position 2
Football is on array position3

Example 3: Associative Array


<?php
$user = [
   "name" => "John",
   "age" => 25,
   "city" => "Delhi"
];
foreach($user as $key => $value) {
   echo $key . " : " . $value . "<br/>";
}
?>

Example 4: Nested Array


<?php
$students = [
   ["name" => "John", "age" => 20],
   ["name" => "Tom", "age" => 22]
];
foreach($students as $student) {
   foreach($student as $key => $value) {
       echo $key . " : " . $value . "<br/>";
   }
   echo "<br/>";
}
?>

Example 5: Using Reference (&)


<?php
$numbers = [1, 2, 3];
foreach($numbers as &$num) {
   $num *= 2;
}
print_r($numbers);
?>

Note: This modifies the original array.

Real-Life Example

Scenario1: Displaying Product List


<?php
$products = ["Laptop", "Mobile", "Tablet"];
foreach($products as $product) {
   echo "<li>" . $product . "</li>";
}
?>

Why this is useful:

  • Used in e-commerce websites
  • Dynamically displays data
  • Simplifies UI rendering

Scenario 2: Processing Form Data


<?php
$_POST = [
   "username" => "John",
   "email" => "john@example.com"
];
foreach($_POST as $key => $value) {
   echo $key . " : " . $value . "<br/>";
}
?>

Note: Useful for handling dynamic form inputs.

Common Mistakes

1. Using foreach on Non-Array


foreach($x as $value)

Note: Error if $x is not an array or object.

2. Forgetting Reference Symbol


foreach($arr as $value) {
   $value *= 2;
}

Note: The original array will not change.

3. Modifying Array Structure Inside Loop

Unsetting or adding elements can cause unexpected behavior.

4. Variable Overwriting

Using the same variable names may cause confusion.

5. Not Using Key When Needed

Sometimes the key is important for logic.

Conclusion

The PHP foreach loop is one of the most powerful and user-friendly looping constructs for working with arrays and objects. It simplifies iteration, reduces errors, and improves code readability.

PHP foreach loop – Interview Questions

Q 1: What is foreach loop?
Ans: Used to iterate over arrays.
Q 2: Syntax of foreach?
Ans: foreach ($arr as $value) { }
Q 3: Can foreach access keys?
Ans: Yes.
Q 4: Is foreach faster than for loop?
Ans: Yes, for arrays.
Q 5: Can foreach modify array values?
Ans: Yes, using references.

PHP foreach loop – Objective Questions (MCQs)

Q1. foreach is used to iterate over ______.






Q2. foreach($arr as $value) loops through ______.






Q3. To get both key and value, syntax is ______.






Q4. Can foreach modify the original array values?






Q5. foreach automatically stops when ______.






Related PHP Tutorials