Performance of for vs foreach in PHP

for Loop: The for loop is an iterative loop which repeats a certain set of code until a specified condition is reached. It is systematically used to execute a set of code for specified number of times, here the number of times denotes the iterator variable.

Syntax:

for( initialization; condition; increment/decrement ) {
    // Set of Code to be iterated and executed
}

The each parameters of for loop have the unique functionalities which are explained below for better understanding:



  • initialization: It is used to initialize the iterator variables, and executed at one time without running the condition statement during the start of the looping condition that is the very first execution of the set of code in the loop.
  • condition: In the beginning of each iteration, condition statement is executed and if the condition returns a true value, the loop continues and the nested statements in the set of code are executed. If the condition evaluates to be false, the execution of the loop gets break at that point of code.
  • increment: It increases the loop counter with a new increment value that is to be evaluated for the condition statement. It is compulsorily executed at the end of each iteration without any break.

Example: This example uses a for loop that starts with $j = 1. The loop will continued until $j is less than, or equal to 5. The variable $j will increase by 1 each time the loop runs.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Loop starts from here 
for($j = 1; $j <= 5; $j++) {
    echo $j . " GeeksforGeeks \n";
}
  
?>

chevron_right


Output:

1 GeeksforGeeks 
2 GeeksforGeeks 
3 GeeksforGeeks 
4 GeeksforGeeks 
5 GeeksforGeeks

foreach Loop: The purpose of foreach loop is to define the use and it specifically iterate over the elements of the array data structure.

Syntax:

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

Below examples illustrate the use of foreach loop.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$students = array( "Jimmy", "Jonny", "Jacky" );
  
// Loop through students array
foreach( $students as $element ) {
    echo $element . "<br>";
}
  
?>

chevron_right


Output:

Jimmy
Jonny
Jacky

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$employee = array(
    "name" => "Robert",
    "email" => "robert112233@mail.com",
    "age" => 18,
    "gender" => "male"
  
);
  
// Loop through employee array
foreach($employee as $key => $element) {
    echo $key . ": " . $element . "<br>";
}
  
?>

chevron_right


Output:

name: Robert
email: robert112233@mail.com
age: 18
gender: male

Performance comparison in for and foreach loop:

  • The for loop is considered to be openly executing the iteration where as the foreach loop hides the iteration and visibly simplified.
  • The foreach loop is considered to be much better in performance to that of the generic for loop.
  • The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.
  • The foreach loop allocates temporary memory for index iterations which makes the over all system to redundant its performance in terms of memory allocation.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to compare the performance
// of for and foreach loop
  
// Declare an array $element
$elements = array();
  
// An array of 100 units with random string values
for($i = 0; $i <= 100; $i++) {
    $units[] = (string)rand(11111, 99999);
}
  
$startingTime = microtime(true);
  
// for loop performance evaluation
for($i = 0; $i < count($units); $i++) { }
  
$endingTime = microtime(true);
$forlooptime = $endingTime - $startingTime;
  
$startingTime = microtime(true);
  
// foreach loop performance evaluation
foreach($units as $unit) { }
  
$endingTime = microtime(true);
$foreachlooptime = $endingTime - $startingTime;
  
echo "for loop evaluates to: " 
. number_format($forlooptime * 1000, 3);
  
echo "\nforeach loop evaluates to: " 
    . number_format($foreachlooptime * 1000, 3);
  
?>

chevron_right


Output:

for loop evaluates to: 0.008
foreach loop evaluates to: 0.003


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.