DEV Community

joshua-brown0010
joshua-brown0010

Posted on

Difference between for and foreach in php

loops are used to enable code reusability, I mean if you need certain lines of code to be executed repeatedly you should use loops to reduce line of code. our topic of discussion is the difference between For loop and for each loop in PHP, let’s explore both one by one in detail.

For loop:

For loop is the most desired and best option when it is known in advance that how many times your script needs to be executed.

syntax and example of for loop:

<?php 
//this is the syntax
for (initialize the counter; test the counter; increment/decrement the counter) {
  script that needs to be executed for iteration;
}
//example 
for ($i=5; $i>=0;$i--)
{
echo "number in decreasing order:$i <br>";
}
?>
Enter fullscreen mode Exit fullscreen mode

Foreach loop

Foreach loop is an ideal choice for Arrays and it works in key and value pairs. The foreach loop executes an array of data with a pair of keys and values up to the last element of the array. besides that, it is used to implement associative arrays and to extract data from the database.Read more

Top comments (0)