PHP ForEach Loop

In PHP, foreach loop works only on arrays and objects & it will issue an error if we try to use it on a variable with a different data type or an uninitialized variable. It is similar to For loop except we don't have to define an incrementer and increment it and there is also no condition to be evaluated. It will run for each item in the array and won't run at all if the array is empty.

It is to be noted that a For Loop and While Loop will continue till some condition is true, the ForEach loop will continue until it has gone through every item in the array.


foreach (array as value)
    //code to be executed;

PHP ForEach Loop Example

$animal = array("cow", "horse", "elephant", "cat"); 
foreach ($animal as $value) {
   echo "$value";

This will produce following result

cow horse elephant cat