PHP foreach Loop
PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax:
foreach($array as $key => $value) { //Statement }
- $array = associative array.
- $key = array key.
- &value = array key`s value.
$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.
<?php $students = array('Henry' => 21, 'George' => 19, 'Jonny' => 15); foreach ($students as $name => $age) { echo $name.' '.$age.'<br/>'; }Output:
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.
<?php $fruits= array("Mango","Orange","Strawberry"); foreach($fruits as $t) { echo $t."<br>"; } ?>Output:
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.
<?php function sub() { $s=array("PHP","JAVA","C","R"); foreach ($s as $a) { echo $a."<br>"; } } sub(); ?>Output:
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.
<?php function fruit($f) { foreach($f as $s) { echo $s."<br>"; } } $f1=array("Apple","Cherry"); fruit($f1); //calling function by passing array ?>Output:
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.