PHP - Statement Foreach loop

Introduction

foreach loop is exclusive for arrays.

It allows you to iterate an array entirely, even if you do not know its keys.

There are two options for the syntax:

Demo

<?php
     $names = ['A', 'B', 'C']; 
     //option 1//from  w w w .j ava2 s  . c  o  m
     foreach ($names as $name) { 
         echo $name . " "; 
     } 
     //option 2
     foreach ($names as $key => $name) { 
         echo $key . " -> " . $name . " "; 
     } 
?>

Result

The foreach loop accepts an array and it specifies a variable which will contain the value of the entry of the array.

We do not need to specify any end condition.

Optionally, you can specify a variable that contains the key of each iteration, as in the second loop.

Related Topics