PHP Tutorial
What is PHP Environment Setup of PHP PHP Syntax PHP Comments PHP Echo & print PHP Variables PHP Scope Variables PHP $ and $$ Variable PHP Constants PHP Operators PHP Data TypesPHP Conditional Statements
PHP Loop Type
PHP Arrays
PHP String PHP FunctionsPHP Form Examples
Form Intro Get & Post Form Validation / Required PHP Complete FormPHP Advanced
PHP Include / Require PHP Date & Time PHP Session PHP Cookies PHP File Handling PHP Open File PHP Read File PHP Write File PHP Append File PHP Delete File PHP File Upload PHP Sending Mail PHP Error HandlingForeach Loop
The foreach
loop - Loops through a block of code for each element in an array. It works only on arrays, and is used to loop through each key/value pair in an array.
Syntax:
foreach( $array as $element )
{
// PHP Code to be executed
}
OR
foreach( $array as $key => $element)
{
// PHP Code to be executed
}
Example 1: PHP program to print the array elements using foreach loop.
<?php
// Declare an array
$array = array("black", "blue", "red", "green");
// Loop through the array elements
foreach ($array as $val) {
echo "$val <br>";
}
?>
- The following example will output the values of the given array ($array):
Output:
black
blue
red
green
Example 2: PHP program to print the associative array elements using foreach loop.
<?php
$customer = array(
"name" => "Kailash",
"email" => "[email protected]",
"age" => 26,
"gender" => "male"
);
// Loop through employee array
foreach($customer as $key => $value)
{
echo $key . ": " . $value. "<br>";
}
?>
-The following example will output both the keys and the values of the given array ($customer):
Output:
name: Kailash
email: [email protected]
age: 26
gender: male
Elevenstech Web Tutorials
Elevenstech Web Tutorials helps you learn coding skills and enhance your skills you want.
As part of Elevenstech's Blog, Elevenstech Web Tutorials contributes to our mission of “helping people learn coding online”.
Read More
Newsletter
Subscribe to get the latest updates from Elevenstech Web Tutorials and stay up to date