(click anywhere to close)
OPEN MENU

[PHP] Loops

category: Website | course: PHP | difficulty:

Sometimes you want a piece of code to be executed a lot of times (especially with arrays). For example, say you wanted to calculate the total price of all items in a shopping cart. Then you could access each item separately, and add that to the total sum, and copy that line of code dozens of times. But, a much easier way would be to put all prices in an array, and execute a single line of code (that accesses the next element in the array and adds the value to the total) lots of times. For this, loops have been invented.

A loop allows you to easily execute the same block of code as many times as you want.

Arrays are the typical use case, but they are applicable everywhere – I promise you, you’ll be writing lots of loops in your programming life. Loops can run indefinitely, or a fixed amount of iterations. And, of course, you can use variables in the loop to slightly change the block of code that’s being executed every time.

While

The while loop is the easiest, and simply keeps looping a block as long as a certain condition returns true.  Just as with if statements, it’s rather intuitive: while this condition is true, keep doing this.

while(condition) { lots of statements }
//SCRIPT: Find all the divisors of a number
$x = 52;
$divisors = [];
$i = 2;

//As long as the following condition is true
while($i <= $x*0.5) {
	//Check if the current number ($i) can divide $x
	if(is_integer($x / $i)) {
		//If so, add it to the divisors array
		array_push($divisors, $i);
	}
	$i++;
}

//The result should be [2,4,13,26], which are all the divisors of 52, so it works!

This loop, however, can keep going on forever – which will freeze the computer or lead to other unpleasant consequences. Therefore, you must make sure that there’s always a possibility that the condition returns false, and you break out of the loop.

Do-While

Another problem with the while loop, is that there’s the possibility that it never runs – not even once – if the condition is false to begin with. To execute a block of statements once with certainty, and then enter a while loop, we use a do-while loop.

do { lots of statements } while (condition);
//Say we want to display a random quote on the homepage, but we don't want the quote to be the same as one we've used the past 3 days
$old_quotes = ["To be or not to be", "Never stop dreaming", "C'est la Vie"];


do {
	$new_quote = //get a new quote from the database...;
} while (in_array($new_quote, $old_quotes));
//... and keep trying for as long as the quote we've chosen is one of the 3 old quotes

As you can see, had the loop from the example been a simple while loop, the variable $new_quote would not exist, so it wouldn't have worked out.

For

When you know exactly how many times you want the loop to run, a for loop is usually better. For example, for loops are typically used to go through elements of an indexed array and do something with them. You know the length of the array, so you know exactly how many iterations you’re going to need. The syntax is

for(initializer; condition; updater){ lots of statements }

The initializer is run once at the start of the loop, and declares a variable and its starting value. This variable is called the iterator, and usually denoted with a simple $i.

The condition is checked at the end of every loop. If it’s still true, it will do another round, if not, it breaks out of the loop.

The updater is called at the end of every loop, and updates one or multiple variables. Usually, it simply increments the iterator (by one).

$shopping_cart = ["Playmobil", "LEGO", "Candy"];

//Loop through all the items within the shopping cart
for($i = 0; $i<sizeof($shopping_cart); $i++) {
	//and display their number and value
	echo "Item $i: $shopping_cart[$i] <br/>";
}

/*The loop should print
	Item 0: Playmobil
	Item 1: LEGO
	Item 2: Candy
*/

You can declare multiple variables in the initializer, as long as you separate them by a comma.

For-Each

The for loop is great for going through indexed arrays, or doing anything else related with numbers, but what if we have an associative array? We use the for-each loop instead. This loop was made specifically for arrays and objects, and goes through all the key-value pairs. There are two syntaxes:

foreach($array as $value) { lots of statements } foreach($array as $key => $value) { lots of statements }

In the first syntax, you can only use the value of the current element. In the second syntax, you can use both the key and the value.

//Say we want to send every user a "personalized" email
$user_list = ["Ginty", "Juan", "Juan's Brother", "Juan's Guineapig", "BATMAN"];

foreach($user_list as $user) {
	$message = "Hello, $user. Thanks for using our service. Regards, the team.";
}

//Now suppose we want to tell the user how many others have signed up for the service before him/her
foreach($user_list as $rank => $user) {
	$message = "Hello, $user. Thanks for using our service. $rank people have gone before you, and are still happy! Regards, the team.";
}

The break Keyword

Sometimes you want to break out of a loop prematurely. For example, if you use a loop on an array to find a certain combination of values, you can stop the loop once it has been found. To exit the current loop, use the break keyword.

If you want to break out of multiple loops at once, you can supply an integer behind the keyword.

$comments = ["Ginty" => "Great post!", "BATMAN" => "I'M BATMAN.", "Juan" => "Wow, I'm never looking at turtles the same way again", "Gandalf" => "Fly, you fools!"];

//We think batman is a very valuable customer, so we want to know if he left a comment
//If so, we don't need to go through the rest of the loop, so we can break out to save resources
foreach($comments as $user => $message) {
	if($user === 'BATMAN') {
		echo "Found him.";
		break;
	}
}

The continue Keyword

Instead of completely breaking out of a loop, you can also choose to go to the next iteration prematurely. For example, you could accidentally have some null values in your array, and if that’s the case you don’t want the rest of the loop code to run (as it will probably throw some errors). To continue to the next iteration, use the continue keyword.

If you want to skip multiple iterations, you can supply an integer behind the keyword.

//Our super secret spy agency seems to have picked up some weird signal that is going through our servers
$signal = "Kthe liSJo7VnC FJhas0 beeEn2Z6 cONoVmpA0HJrComiYsed. i 93rYepOZeaEHt,6 tPhH52HYe lioVTn hasXJ BPbeeTTnK V2cKLomIpr7Y3TSom85ised.";

//Juan thinks that we can retrieve the original message by cutting away all numbers and capital letters
$actual_message = "";
for($i = 0;$i<strlen($signal);$i++) {
	//If it's an integer, continue
	if(is_integer($signal[$i])) {
		continue;
	}
	//If transforming the letter to uppercase doesn't change anything, it's a capital letter, so continue
	if($signal[$i] != " " && strtoupper($signal[$i]) === $signal[$i]) {
		continue;
	}
	//Otherwise, we've found a piece of the original message
	$actual_message .= $signal[$i];
}

//Test it yourself to find the original message!
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)