PHP loops

There are a few different loops in PHP.

  • while
  • do while
  • for
  • foreach

Let’s run through each one and see how to use them.

while

It just goes until the condition at the beginning in the brackets is true – think of it as an if statement.

<?php

$x = 0;

while ($x < 10) {
	echo "I’ll loop 10 times. - " . $x;
	$x++;
}

?>

Make sure you’re condition will ever be met, otherwise it’ll loop indefinitely until PHP times out after 30 seconds.

do while

The same as the above, except the first iteration always runs and it is only after the first iteration and before the second that the condition is checked.

<?php

$x = 0;

do {
	echo "I’ll loop 10 times. - " . $x;
	$x++;
} while ($x < 10)

?>

for

In a for loop, we initate a counter, set where the counter must stop and choose how to increment the counter.

<?php

// Start 0 | Stop 9 | Add 1 each time
for ($i = 0; $i < 10; $i++) {
	echo $i;
}

// Start 10 | Stop 1 | Minus 1 each time
for ($i = 10; $i > 0; $i--) {
	echo $i;
}

// Increment by a different number
for ($i = 0; $i < 100; $i = $i + 10) {
	echo $i;
}

?>

And using it on an array.

<?php

$arr = ["a", "b", "c", "d"]

// Increment by a different number
for ($i = 0; $i < count($arr); $i++) {
	echo $arr[$i] . "\n";
}

?>

foreach

Lastly, we use foreach loops to iterate over arrays.

With keys

<?php

$arr = array("a" => "b", "b" => "c", "c" => "d");

foreach($arr as $key => $value) {
	echo $key . " - " . $value . "\n";
}

?>

Without keys

<?php

$arr = ["a", "b", "c"];

foreach($arr as $value) {
	echo $value . ", ";
}

?>

break

To prematurely stop a loop, you can use break within an if statement.

<?php

$arr = ["a", "b", "c"];

// It’ll get to "b", won’t output it, and then end
foreach($arr as $value) {
	if($value == "b") {
		break;
	}
	echo $value . ", ";
}

?>

continue

If you want to skip an iteration, use continue conditionally.

<?php

$arr = ["a", "b", "c"];

// It’ll get to "b", won’t output it, and then move on to "c"
foreach($arr as $value) {
	if($value == "b") {
		continue;
	}
	echo $value . ", ";
}

?>

That’s it, now you know how to use loops in PHP.

Share