While you were out - while loops in PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

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

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles