Loops

Loops execute the same code repeatedly as long as a condition is true.

In PHP, we have while, do-while, for, and foreach loop.

I. while loop

while loops through a block of code as long as the condition is true.

Syntax

while (condition is true) {
  // do something
}

Example

$i = 1
while ($i <= 10) {
  echo $i++;
}
// Output: 12345678910

II. do…while loop

do...while loops through a block of code once, and repeats the loop as long as the condition is true.

Syntax

do {
  // do something
} while (condition is true);

Example

$i = 2;
do {
  echo $i;
} while ($i < 1);
// Output: 2

III. for loop

for loop loops through a block of code a specified number of times.

Syntax

for (init counter; condition; increment counter) {
  // do something
}

Example

for ($i = 0; $i <= 5; $i++) {
  echo $i;
}
// Output: 012345

Looping through an array

$array = [1, 2, 3, 4];
for ($i = 0; $i < count($array); $i++) {
  echo $array[$i];
}
// Output: 1234

We can assign a variable to the array length to improve the performance, especially if an array has many items.

$array = [1, 2, 3, 4];
$length=count($array);

for ($i = 0; $i < $length; $i++) {
  echo $array[$i];
}
// Output: 1234

IV. foreach

foreach loop can iterate over an array or object.

Syntax

foreach ($array as $value) {
  // do something
}

Example

$languages = ["English", "German", "Spanish"];

foreach ($languages as $lang) {
  echo "$lang <br>";
}
/*
English
German
Spanish
*/

$scores = ["English" => 9, "German" => 9.5, "Spanish" => 8];
foreach ($scores as $key => $value) {
  echo "$key: $value <br>";
}
/*
English: 9
German: 9.5
Spanish: 8
*/

Loop through an associative array

We can use the function implode() or json_encode() to loop through an associative array.

$person = [
  "name" => "Dev",
  "email" => "dev@gmail.com",
  "skills" => ["react", "php", "wordpress"],
];

/* Using json_encode
foreach ($person as $key => $value) {
  echo $key.": ".json_encode($value)." <br>";
}

*/

// Using implode()

foreach ($person as $key => $value) {
  if (is_array($value)) {
    $value = implode (", ", $value);
  }
  echo "$key: $value <br>";
}

/* Output
name: Dev
email: dev@gmail.com
skills: react, php, wordpress
*/

V. Breaking out of a Loop

The break statement ends the current loop and jumps to the statement immediately following the loop.

for ($count = 1; $count <= 10; $count++ ) {
  if ( $count == 5 ) break;
  echo "Count: $count";
}
echo "Done";
/* Output:
Count: 1
Count: 2
Count: 3
Count: 4
Done
*/

VI. continue keyword

The continue statement ends the current iteration, jumps to the top of the loop, and starts the next iteration.

for($count=1; $count<=10; $count++ ) {
  if ( ($count % 2) == 0 ) continue;
  echo "Count: $count\n";
}
echo "Done\n";
/* Output:
Count: 1
Count: 3
Count: 5
Count: 7
Count: 9
Done
*/