PHP For and Foreach Loop

In this tutorial, we are going to discuss more complex loops through which we can get more control on the overall looping process. Consider a situation where you want to have a counter which should follow specific function and some conditions must be evaluated for it. Although you can use while loop but it may get difficult to make this structure. For loops makes it easier for you. The general parts of it are shown in following code:

<?php

for ( 1 ; 2 ; 3){

};

?>

For Loop Parameters:

  • init counter: Initialize the loop counter value
  • increment counter: Increases the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

The expression initialization is assessed once i.e. at the starting of the for loop. Each time the loop is executed, the expression condition is tested. Assuming that it is true, the body of the loop executed; provided that it is false, the loop ends. The expression increment is assessed each time after the loop form runs.

It is like:

for (initialization; condition; increment) 
{
code to be executed;
}

PHP For loop takes three expressions inside its parentheses, split by semi-colons. The point when PHP For loop executes, this happens:

  1. The first place is for defining a counter variable and setting initial value for it. Then the initializing expression is executed. This expression ordinarily initializes one or more loop counters, yet the syntax permits an expression of any level of complexity.

If you have a proper variable before, you can leave it empty. If you have two or more counter variables that should go with each other you can define them here with comma for separation

  1. The condition expression is assessed. Assuming that the value of condition is true, the loop statements execute and if the value of condition is false, the For loop terminates.
  2. The update expression increment executes.
  3. The loop execute, and control comes back to step 2.

The example below displays the numbers from 0 to 5:

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x 
";
}
?>

Out Put

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

The PHP foreach Loop:

Foreach is a kind of for loop and designed for arrays. With it we can access array values from the first index to the end. It doesn’t need setting initial value or stopping condition. It goes array indexes one after another.

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntax:

Syntax

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. It is specifying an array name which you want to access its elements. $value is a variable that is equal to array elements, in fact it is a copy of the array values in each cycle and change in each iteration.

On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).

The second form will additionally assign the current element’s key to the $key variable on each iteration.

The following example demonstrates a loop that will output the values of the given array ($colors):

Example

$email = array('
 sam@example.com', '
 alex@example.com');
foreach ($email as $value) 
{
 echo "Processing ".$value;
}

Output will be:

Processing sam@example.com
Processing alex@example.com

PHP executes the body of the loop once for every element of $email in turn, with $value set to the present element. Elements are handled by their inside request. Looping proceeds until the Foreach loop achieves the final elementor upper bound of the given array.

An alternative form of PHP Foreach loop gives you access to the current key:

$person = array('Name' => 'Andrew', 'Age' => 21, 'Address' => '77, Lincoln st.');
foreach ($person as $key => $value) 
{
   echo $key." is ".$value."";
}

Output will be:

 Name is Andrew 
 Age is 21 
 Address is 77, Lincoln st.

How to Break foreach loops :

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do ‘break 3’ to get out of all three nested loops. This will work for the ‘for’, ‘foreach’, ‘while’, ‘do-while’, or ‘switch’ structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
 foreach($department as $dKey=>$group)
 {
 foreach($group as $gKey=>$employee)
 {
 if ($employee['fullname'] == $person)
 {
 $found = true;
 break 3;
 }
 } // group
 } // department
} // organization

You are familiar with ‘break’ from before. But we want to speak some more about it here.

If you want to get out from two foreach or other loops, just mention the number of the loops after ‘break’.

It is possible that jumping from one iteration of a loop or more than one loop. The proper code is ‘continue num’ again the num does what it has done for break. This code tells PHP to ignore the remainder of this loop and start new iteration. Look at the example:


$a=array('x'=>'Math',  'y'=>'Science' ,'z'=>'Art');

$b=array(1=>'Mike' ,2=>'John' , 3=>'Peter');

foreach ($b as $i){

  foreach ($a as $j){

    echo $i.'-'.$j;

          if ($i.$j=='JohnMath')  

        {
echo''; continue 2; }
}

          echo '';

}

Result:

Mike-Math
Mike-Science
Mike-Art

 Peter-Math
 Peter-Science
 Peter-Art

Here we wanted to escape from resuming second group about John; so we have gone to the next line by ‘<br>’ and gotten rid of second and first loop remainder by ‘continue 2’.

Don’t forget to add semicolon after ‘continue’; it leads to some confusion and some malfunctions are resulted.

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com