Skip to content

do

The PHP "do" Keyword: A Comprehensive Guide

The do keyword is part of the do-while loop control structure in PHP. It executes a block of code repeatedly while a specified condition remains true, and stops when the condition becomes false. Unlike a standard while loop, a do-while loop always executes the block at least once before checking the condition. In this article, we will explore the syntax and usage of the do-while loop in depth, and provide plenty of examples to help you master this important PHP feature.

Syntax

The do keyword is used in conjunction with the while keyword to create a do-while loop. Here is the basic syntax for using it in PHP:

The PHP syntax of do

php
<?php

do {
  // code to be executed
} while (condition);

In this example, the do keyword executes the block of code first, then evaluates the condition to decide whether to repeat.

Examples

Let's look at some practical examples of how the do keyword can be used:

Examples of PHP do

php
<?php

// Example 1
$myNumber = 1;
do {
  echo $myNumber . PHP_EOL;
  $myNumber++;
} while ($myNumber <= 5);

// Output: 1 2 3 4 5

// Example 2
$myArray = ["apple", "banana", "cherry", "date"];
$index = 0;
do {
  echo $myArray[$index] . PHP_EOL;
  $index++;
} while ($index < count($myArray));

// Output: apple banana cherry date

In these examples, we use the do-while loop to iterate through values while the condition evaluates to true.

Benefits

Using the do-while loop has several benefits, including:

  • Guaranteed execution: The code block runs at least once before the condition is evaluated, making it ideal for input validation or menu displays.
  • Cleaner syntax: It eliminates the need for duplicate code or separate initialization steps often required with standard while loops.

Conclusion

In conclusion, the do-while loop is a reliable control structure for PHP developers, ensuring a block of code executes at least once while continuing as long as a condition remains true. We hope this guide has been helpful, and we wish you the best of luck as you continue to develop your PHP skills.

Practice

In PHP, what is the purpose of the 'do-while' loop?

Dual-run preview — compare with live Symfony routes.