Repeat

For Loop

PHP

 

For loop

PHP 5
for ($count=5; $count>0; $count--) {
  
    print($count);
  
}

for statement is a handy syntax for iterating through arrays and iteratable objects. Below is the most common syntax used:

for (<initialize>; <condition>; <modification>) {
    <code block>
}

The for loop above executes in the order below:

  1. Execute <initialize>
  2. If <condition> evaluates to true execute the <code block>
  3. Execute <modification>
  4. Go to Step 2

This will print 5 4 3 2 1 on Console.

 

Single For loop Statement

PHP 5
for ($count=5; $count>0; $count--)
    print($count);

If you only have one statement in your for block, you can drop the curly braces { }.

This will print 5 4 3 2 1 on Console.

 

ForEach loop on Indexed Array

PHP 5
$arr = [10, 11, 12];

foreach($arr as $value) {
  print($value);
}

foreach($arr as $index => $value) {
  print($index . ":" . $value);
}

The foreach() function lets you iterate through array elements in an elegant syntax.

First foreach will print 10 11 12 on Console.
Second foreach will print 0:10 1:11 2:12 on Console.

 

ForEach loop on Associative Array

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

foreach($arr as $key => $value) {
  print($key . ':' . $value);
}

The foreach() function lets you iterate through Associative Array key/value pairs.

This will print name:Sam age:25 on Console.

 

ForEach loop on object

PHP 5
$obj = new stdClass;
$obj->name = 'Sam';
$obj->age = 25;

foreach($obj as $key => $value) {
  print($key . ':' . $value);
}

The foreach() function can also be used to iterate through object properties.

Classes can also implement the interface Iterator to control the foreach execution.

This will print name:Sam age:25 on Console.