Foreach structure

Foreach-as with arrays

You could iterate through elements in array and do actions for each of those element musing foreach and at.

foreach <array>
<action for each element>

$_key and $_value will be created to ley you access key and value of the array.

$list:[“Annie”,”Bob”, “John”, “Sabrina”]

foreach $list

     @echo $_key ". " $_value. "\n"

//\n is the end of line.

> 0. Annie

> 1. Bob

> 2. John

> 3. Sabrina

 

In case you need both the key and the value of each element:

foreach <array> as <element’s value holding var>  

               <action for each element>

$list:["Annie","Bob", "John", "Sabrina"]

foreach $list as $name

     @echo $name + "\n" // \n is the end of output line.

> Annie

> Bob

> John

> Sabrina

 

In case you need only the value of each element:

foreach <array> as < element’s key holding var> => <element’s value holding var>

               <action for each element>

Ex: write out all name in an array which is a list of names.

Now, write out all name in an array which is a list of names with it’s index.

$list : ["Annie","Bob", "John", "Sabrina"]

foreach $list as $index $name

     @echo $index ". " $name + "\n

> 1. Annie

> 2. Bob

> 3. John

> 4. Sabrina