You are currently viewing What is foreach Loop in PHP | How to Use it Explained
  • Post category:PHP

What is foreach Loop in PHP | How to Use it Explained

What is foreach loop in php

In this article, we will see what is foreach loop in PHP examples.

For each loop

To traverse (or loop through) an array of elements, we use foreach loop.

Syntax1:

foreach($arrayName as $variablename)
{
statement;
}

Syntax2:

foreach($arrayName as $variablename):
statement;
endforeach;

Example1:

<?php
$names = array("manju", "ravi", "rama");

foreach($names as $value)
{
echo $value;
}

/*
Output:
manju
ravi
rama
*/
?>

Example2:

<?php
$names = array("manju", "ravi", "rama");
foreach($names as $value):
echo $value;
endforeach;

/*
Output:
manju
ravi
rama
*/
?>

Steps:

  1. Above both PHP examples, we have executed the same process of program execution.
  2. First, we have created an array with three values.
  3. Then, we use “foreach” loop and print values. So, the output is displayed array values like manju ,ravi, drama one by one.
  4. We can also print $key in foreach loop and see the examples below to print the index of an array.

Print index of an array using foreachloop

<?php
  $names = array("manju", "ravi", "rama");

  foreach($names  as  $key => $value)
  {
      echo $key," ",$value,"<br/>;
  }

/*
Output:
manju
ravi
rama
*/
?>

See the above code, we printed value with index number of an array using $key => $value as in the above code.

Leave a Reply