foreach array in PHP programming

foreach statement is used for making loop over array in loop. It will work only with arrays, and will make errors if we try it with other data types.

foreach statement can be used in two ways.. See the following two structures of foreach loop in PHP

foreach (array as $value)
{
// Operation statement
}

foreach (array as $key => $value)
{
// Operation statement
}

Difference between these two syntax are

  • In the first “foreach” statement , value of each array’s element will be assigned to the variable $value
  • In the second “foreach” statement, key of each array’s element will be assigned to the variable $key

See the sample PHP programs with foreach array loop structure

<?php
$arr = array(10, 20, 30, 40);
foreach ($arr as $value) {
    echo $value." ";
}
?>

Its output will be the values of each elements in array :
10 20 30 40

<?php
$arr = array(10, 20, 30, 40);
foreach ($arr as $key => $value) {
    echo $key." ";
}
?>

Its output will be the key vof each elements in array :
0 1 2 3

When “foreach statement” execute internal pointer will initialize to the first record of array and we don’t need to rest the arrays before the “foreach loop operation”

Share

One thought on “foreach array in PHP programming”

Comments are closed.

Share
Share