PHP Foreach Loop

PHP For Loop Previous Next PHP Break


PHP ForEach - loops through a block of code for each element in an array.

Syntax


foreach($array as $value){ // code to be executed }

Here is the code of php foreach loop.

Filename: php / foreach-loop.php


Code
<?php
$lang=array("English","Spanish","French");
foreach($lang as $value){
echo $value . "
"; } ?>

Running Step.


Type Url - https://localhost/php/foreach-loop.php

Output
English
Spanish
French

PHP Foreach Without <br> Tag.


PHP foreach without <br> tag will print data in one same line.

In below code we used comma to seperate data.

Filename: php / foreach-loop1.php


Code
<?php
$lang=array("English","Spanish","French");
foreach($lang as $value){
echo $value.",";
}
?>

Running Step.


Type Url - https://localhost/php/foreach-loop1.php

Output
English,Spanish,French

PHP Foreach Array Reverse


PHP foreach array reverse will display data in reverse order means last element of array will print first and first array element will print last.

array_reverse($array; function is used to reverse array.

Filename: php / foreach-loop2.php


Code
<?php
$array=array("English","Spanish","French");
foreach(array_reverse($array) as $value){
echo $value . "
"; } ?>

Running Step.


Type Url - https://localhost/php/foreach-loop2.php

Output
French
Spanish
English

PHP Foreach Array Reverse without <br> Tag.


PHP foreach array reverse without <br> tag will print data in same line.

In below code we used comma to seperate data.

Filename: php / foreach-loop3.php


Code
<?php
$array=array("English","Spanish","French");
foreach(array_reverse($array) as $value){
echo $value . ",";
}
?>

Running Step.


Type Url - https://localhost/php/foreach-loop3.php

Output
French,Spanish,English

Tags: PHP


Was this helpful ?

Related Code


Popular Code

Latest Code