Loops In PHP

foreach Loop in PHP

The foreach loop work with arrays. For every iteration the value of the array element is assigned to a variable and then execute the statement in the body of foreach loop. The foreach loop repeated until the array pointer reaches the last array element.
foreach loop work with two syntax:
First Syntax:
foreach (array_expression as $value)
{
statement1;
statement2;
--
--
}
The first form loops over the array given by array_expression. On each iteration the value of the current element is assigned to $value and the internal array pointer is moved to next position in Array .
For Example if we have an array contains the name of students:


<?php

$name = array('Majeed','Saleem', 'qasim', 'Shah');

foreach ($name as $value)

 {

 echo $value . '<br>";

 }

?>

This loop display each name of the array on screen.
2nd Synatx:
foreach (array_expression as $key => $value)
{
statement
}
The second syntax will additionally assign the current element's key to the $key variable on each iteration.
Example of second syntax is :


$studentmarks;
 

$employeeAges["qaism"] = "328";
$employeeAges["aslam"] = "216";
$employeeAges["majid"] = "350";
$employeeAges["saleem"] = "456";
 

foreach( $studentmarks as $name => $age)

{
echo "Name: $name, Age: $age <br />";
}

This will be display:

Name: Qasim, Age: 28
Name: Aslam, Age: 16
Name: Majid, Age: 35
Name: Saleem, Age: 46