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:
"; } ?>
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
"; }
This will be display:
Name: Qasim, Age: 28
Name: Aslam, Age: 16
Name: Majid, Age: 35
Name: Saleem, Age: 46
Variables in PHP
PHP Concatenation
Calculation in PHP
If Statements in PHP
if ... else Statements in PHP
Nested IF Structure in PHP
PHP Comparison Operators
Switch Statement in PHP
Logical Operators In PHP
PHP Booleans
FOR Loop in PHP
While Loop In PHP
foreach Loop In PHP
Break Statement
Array In PHP
Associative Array
The Count function
Changing Case Function
Trim Function In PHP
Str_shuffle( ) function
strpos function in PHP
Explode() Function in PHP
Function
Passing Function Arguments
Server Variables
Header Function
Include Function
The require Function