Unlike a for loop, the PHP foreach loop works only with arrays and objects. The foreach loop starts with the first element of the array and during each iteration, next array element is fetched.

A PHP foreach loop has two syntaxes:

First syntax

foreach(array_name as $value)
{
//statements
}

This syntax is used to access the elements of an array without index value.

Example

<?php
$MyArray = array(1,2,3);
foreach($MyArray as $val)
{
echo $val;
}
?>

Output

1
2
3

Second syntax

foreach(array_name as $key => $value)
{
statement
}

This syntax is used to access the elements of an array with index value.

Example

$numbers = array("one"=>1, "two"=>2,"three"=>3);
foreach($numbers as $key => $value)
{
echo $key ."->". $value."<br>";
}

Output

one->1
two->2
three->3