Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the difference between for and Foreach loop in PHP ?

  • Last Updated : 21 Oct, 2021

Loops can be used to iterate over collection objects in PHP. The for and foreach loop can be used to iterate over the elements.

for loop: The for loop works at the end of the given condition. It is used for the implementation of variables and works in a single way. The for loop does not work in the case of associative arrays. A for loop basically consists of three portions or parts. 

  •  A variable is initialized with a value.
  • The variable is subjected to the condition to which it is compared.
  • Increment/decrement loop counter.
for(expr1; expr2; expr3) {
    // Perform action
}

Example 1:

PHP




<?php
  
// Declaring an array
$arr = array(1, 2, 3, 4, 5);
  
// Looping over array
for($i = 0; $i < 5; $i++) {
  
// Accessing individual elements
    echo($arr[$i] . "  ");
}
  
?>

Output:

1  2  3  4  5 

foreach loop: The foreach loop works at the end of the array count. This loop can work with variables as well as associative arrays. Therefore, this loop can be implemented in more than one way. The foreach loop is much better and performs better in comparison to the for loop. 



foreach ($array as $value) {
    // Perform action
}

Example 2:

PHP




<?php
  
// Declaring an array
$arr = array(1, 2, 3, 4, 5);
  
// Looping over array
foreach($arr as $val){
  
    // Accessing individual elements
    echo($val . "  ");
}
  
?>

Output:

1  2  3  4  5 

This loop can also be implemented in the case of key-value pairs, i.e. associative arrays. The key and their corresponding mapped values can be displayed easily on the screen. The following code snippet illustrates the usage of the loop over an associative arrays.

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

Example 3:

PHP




<?php
  
// Declaring an array
$arr = array();
$arr["Java"] = "Spring Boot";
$arr["PHP"] = "CodeIgniter";
$arr["Python"] = "Django";
  
// Looping over array
foreach($arr as $key => $val) {
  
    // Accessing individual elements
    echo($key . " : " . $val . "<br>");
}
  
?>

Output:

Java : Spring Boot
PHP : CodeIgniter
Python : Django
                                                   for loop                                 foreach loop
The iteration is clearly visible.The iteration is hidden.
Good performance.Better performance.
The stop condition is specified easily.The stop condition has to be explicitly specified.
Upon working with collections, it needs the usage of the count() function. It can simply work without the usage of the count() method. 



My Personal Notes arrow_drop_up
Recommended Articles
Page :