Difference Between For and Foreach in PHP

In this post, we will understand the differences between for and foreach loops in PHP −

The 'for' Loop

It is an iterative loop that repeats a set of code till a specified condition is reached. It is used to execute a set of code for a specific number of times. Here, the number of times is controlled by the iterator variable.

Syntax

for( initialization; condition; increment/decrement ) {
    // code to iterate and execute
}
  • Initialization: It is used to initialize the iterator variables. It also helps execute them one at a time without running the conditional statement at the beginning of the loop's condition.
  • Condition: This statement is executed and if the condition returns a True value, the loop continues and the statements within it are executed. If the condition gives a False value, the execution comes out of the loop.
  • Increment: It increments/increases the counter in the loop. It is executed at the end of every iteration without a break.

Example

Let us see an example −

<?php
for($i = 1; $i <= 2; $i++) {
    echo $i . " Hi <br>";
}
?>
1 Hi 
2 Hi 

The 'foreach' Loop

The foreach loop is specifically designed to iterate over arrays and objects. It provides a simpler and more efficient way to traverse data structures without manually managing counters.

Syntax

foreach( $array as $element ) {
    // PHP Code to execute
}
foreach( $array as $key => $element) {
    // PHP Code to execute
}

Example

<?php
$people = array( "Will", "Jane", "Harold" );
foreach( $people as $element ) {
    echo $element . "<br>";
}
?>
Will<br>Jane<br>Harold<br>

Key Differences

Aspect for Loop foreach Loop
Purpose General iteration with counter Array/object iteration
Complexity More complex syntax Simple and clean
Performance Slower for arrays Faster for arrays
Counter Visibility Manual counter management Hidden iteration

Conclusion

Use for loops when you need precise counter control and foreach loops when iterating over arrays or objects. The foreach loop is generally preferred for array traversal due to its simplicity and better performance.

Updated on: 2026-03-15T09:39:28+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements