How to use foreach Loop in PHP

In this article, I will explain how the foreach Loop can be used in PHP.
  • 1988

foreach Loop in PHP

  • The foreach loop is used to loop through arrays.

  • The foreach looping is the best way to access each key/value pair from an array.

Syntax

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

In forech loop, every iteration, the value of the current array element is assigned to $value and the array pointer is moved by one so on the next loop iteration.

Example

In the following example both the keys and values of an array have accessed.

<html>

<body>

<h2 style="color: steelblue;">foreach Loop example</h2>

    <?php 

    $personal_details=array("Name" => "Sachin Bhardwaj", "Occupation" => "Engineer", 'Age' => 25, "Country" => "India"); 

    foreach ( $personal_details as $key => $value ) 

    { 

    echo ("$key=>$value<br />"); 

    } 

    ?> 

</body>

</html>

 

Output

for-each.jpg

You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2019 DotNetHeaven. All rights reserved.