PHP foreach Loop with Example
PHP foreach loop is used to loop through the associative arrays.
Syntax:
1 2 3 4 5 6 |
foreach($array as $key => $value) { //Statement } |
- $array = associative array.
- $key = array key.
- &value = array key
s value.
$key and $value variables can be named anything. The $key will be equal to the arrays key, and $value will be equal to that key`s value.
The loop ends when the last array key (=>) value pair reached.
Associative Array Example:
1 2 3 |
$arrayname = array(‘key’ =>value, ‘key’ =>value); |
Associative array have named keys. The key names are placed inside single or double quotes and the (=>) is used to assign key value pairs.
1 2 3 4 5 6 7 |
<?php $students = array('Henry' => 21, 'George' => 19, 'Jonny' => 15); foreach ($students as $name => $age) { echo $name.' '.$age.'<br/>'; } |
Output:
1 2 3 4 5 |
Henry 21 George 19 Jonny 15 |
- In the above program, we are using an associative array here $students with three keys/values, and we are printing the value of each array element through a foreach loop and an echo function for printing results.
Example2:
1 2 3 4 5 6 7 8 9 |
<?php $fruits= array("Mango","Orange","Strawberry"); foreach($fruits as $t) { echo $t."<br>"; } ?> |
Output:
1 2 3 4 5 |
Mango Orange Strawberry |
- In the above program, an array of$fruits contains three elements. For each loop iteration, here the value of current array element is assigning to the variable $t, an array pointer is moving by one and displaying the value of each array element until the last array element found.
Example3:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php function sub() { $s=array("PHP","JAVA","C","R"); foreach ($s as $a) { echo $a."<br>"; } } sub(); ?> |
Output:
1 2 3 4 5 6 |
PHP JAVA C R |
- In the above program, we are using a user-defined function sub, and the function body is containing an array $s with four elements, and we are displaying the value of each array element using a foreach loop.
Example4:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php function fruit($f) { foreach($f as $s) { echo $s."<br>"; } } $f1=array("Apple","Cherry"); fruit($f1); //calling function by passing array ?> |
Output:
1 2 3 4 |
Apple Cherry |
- In the above, program is containing a user-defined function fruit, and an array is passing as an argument to the function. The function is containing a foreach loop, through this loop we are displaying the value of each array element with an echo statement. When a function is called, then the function body will be executed.