php tutorial - PHP Foreach Loop - php programming - learn php - php code - php script



  • The foreach construct provides an easy way to iterate over arrays.
  • foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data types or an uninitialized variable.
  • The foreach loop is a variation of the for loop. It will loop through an entire array, performing the specified actions for each value in the array.
 For Each loop

Learn PHP - PHP tutorial - For Each loop - PHP examples - PHP programs

php programming Syntax :

foreach ($array as $value)
{
    code to be executed;
}
click below button to copy the code. php tutorial - team

  • Foreach : The foreach loop runs for all elements of an array.
  • $array : $array is the array variable given by array expression.
  • $value : $value specifies that for every loop the value of the current element is assigned to $value.
php - php 7 - php tutorial - php framework tutorial - php examples - php sample code - php basics - php web development - php components - php project - php technology  - learn php - php online - php programming - php program - php code - html code - embedded php in html - for-each-loop

learn php Sample Code : a simple php program

<!DOCTYPE html>
<html>
    <head>
        <title>Foreach-Loop</title>
    </head>
    <body>
        <?php
            $x=array("1","2","3","4");
            foreach ($x as $value)
            {
                echo $value . "<br />";
            }
        ?>
    </body>
</html>
click below button to copy the code. php tutorial - team

php for beginners Code Explanation :

Code Explanation for foreach Loop In PHP

  1. In PHP, $x=array("1","2","3","4") specify that to value of the current array element is assigned to $value.
  2. Here, foreach ($x as $value) specify an array pointer is moved by one, until it reaches the last array element.

php coding Sample Output :

output for foreach Loop In PHP

  1. Here in this output the array element 1,2,3,4 will be printed until it reaches the last array element “4”.


Related Searches to php foreach loop