Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Performance of FOR vs FOREACH in PHP
The performance difference between for and foreach loops in PHP has been a topic of debate among developers. While foreach was historically slower due to array copying, modern PHP versions have optimized this significantly.
Performance Comparison
Let's compare the execution time of for vs foreach loops with a practical example −
<?php
$my_arr = array();
for ($i = 0; $i < 10000; $i++) {
$my_arr[] = $i;
}
// Test foreach with value modification
$start = microtime(true);
foreach ($my_arr as $k => $v) {
$my_arr[$k] = $v + 1;
}
echo "Foreach (copy): " . (microtime(true) - $start) . " seconds
";
// Test foreach with reference modification
$start = microtime(true);
foreach ($my_arr as $k => &$v) {
$v = $v + 1;
}
echo "Foreach (reference): " . (microtime(true) - $start) . " seconds
";
// Test traditional for loop
$start = microtime(true);
for ($i = 0; $i < count($my_arr); $i++) {
$my_arr[$i] = $my_arr[$i] + 1;
}
echo "For loop: " . (microtime(true) - $start) . " seconds
";
// Test optimized for loop
$count = count($my_arr);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
$my_arr[$i] = $my_arr[$i] + 1;
}
echo "For loop (optimized): " . (microtime(true) - $start) . " seconds
";
?>
Output
Foreach (copy): 0.0012 seconds Foreach (reference): 0.0008 seconds For loop: 0.0015 seconds For loop (optimized): 0.0009 seconds
Key Performance Factors
| Loop Type | Memory Usage | Speed | Best For |
|---|---|---|---|
| foreach (by value) | Higher (creates copies) | Good | Read-only operations |
| foreach (by reference) | Lower | Faster | Modifying array values |
| for loop | Lowest | Fastest (when optimized) | Numeric indexed arrays |
Best Practices
Use foreach with references when modifying array values to avoid copying. For simple iterations without modification, both loops perform similarly in modern PHP. Choose for loops for numeric arrays when you need index control.
Conclusion
While for loops can be slightly faster for large datasets, foreach offers better readability and is optimized in modern PHP. The performance difference is negligible for most applications, so prioritize code clarity over micro-optimizations.
