While you were out – while loops in PHP

while loops are considered the simplest type of loop in PHP-dom. Their purpose is to continue to execute until a condition has been met. Let’s look at an example related to the title, a pseudo-script that will collect messages while you’re out, returning at 1pm (like a lunch break ;):

$out = true

while ($out)
{
	// Some logic to receive messages

	if (date('Hi') >= 1300)
	{
		$out = false
	}
}

The script will indefinitely run until the time is 1pm or later. While loops are great in situation where you’re either waiting around for something and want to continue checking for it or times when you’re iterating through an object or array attempting to find a specific value or if you’re totaling values and want to stop when you reach a certain threshold.

Like most things PHP, there is alternate syntax for while loops (this syntax is very prominent within WordPress):

$i = 0
while ($i < 10):
	$i++
endwhile

This alternate syntax works well when working within an HTML template as the syntax only takes up a single line to start or end the while and the endwhile; is significantly more verbose than a closing } especially when dealing with longer blocks of markup.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.