PHP - Do...While Loop: A Beginner's Guide

Welcome, aspiring coders! Today, we're diving into the exciting world of PHP loops, specifically the do...while loop. As your friendly neighborhood computer teacher, I'm here to guide you through this concept with plenty of examples and explanations. So, grab your virtual notepads, and let's get looping!

PHP - Do…While Loop

What is a Do...While Loop?

Before we jump into examples, let's understand what a do...while loop is. Imagine you're playing a game where you have to keep rolling a dice until you get a six. You'll roll the dice at least once, right? That's exactly how a do...while loop works!

A do...while loop executes a block of code at least once before checking if a condition is true. If the condition is true, it continues to execute the block repeatedly until the condition becomes false.

Now, let's look at the syntax:

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

Example 1: Basic Do...While Loop

Let's start with a simple example:

<?php
$i = 1;
do {
    echo "The number is: $i <br>";
    $i++;
} while ($i <= 5);
?>

What's happening here?

  1. We initialize a variable $i with the value 1.
  2. The loop starts with do, and we echo the current value of $i.
  3. We increment $i by 1 using $i++.
  4. After the closing brace, we have the while condition. It checks if $i is less than or equal to 5.
  5. If the condition is true, the loop continues; if false, it stops.

Output:

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

Example 2: Do...While Loop with User Input

Let's make things more interactive! We'll create a simple guessing game:

<?php
$secretNumber = 7;
do {
    $guess = (int)readline("Guess the number (between 1 and 10): ");
    if ($guess < $secretNumber) {
        echo "Too low! Try again.\n";
    } elseif ($guess > $secretNumber) {
        echo "Too high! Try again.\n";
    }
} while ($guess != $secretNumber);

echo "Congratulations! You guessed it right!";
?>

In this example:

  1. We set a secret number (7 in this case).
  2. The loop asks the user to guess the number.
  3. It provides feedback if the guess is too low or too high.
  4. The loop continues until the correct number is guessed.

This demonstrates how do...while loops can be used for input validation and creating simple games!

Example 3: File Reading with Do...While Loop

Let's explore a more practical example - reading lines from a file:

<?php
$file = fopen("sample.txt", "r");

do {
    $line = fgets($file);
    if ($line !== false) {
        echo $line . "<br>";
    }
} while ($line !== false);

fclose($file);
?>

Here's what's happening:

  1. We open a file named "sample.txt" in read mode.
  2. The loop reads a line from the file using fgets().
  3. If the line is not false (i.e., not end of file), we echo it.
  4. The loop continues until we reach the end of the file.
  5. Finally, we close the file.

This example shows how do...while loops can be useful for file operations!

Decrementing a "do...while" Loop

Now, let's count backwards using a do...while loop:

<?php
$countdown = 5;

do {
    echo "T-minus $countdown...<br>";
    $countdown--;
} while ($countdown > 0);

echo "Blast off! ?";
?>

In this cosmic countdown:

  1. We start with $countdown set to 5.
  2. The loop prints the current countdown number.
  3. We decrement $countdown using $countdown--.
  4. The loop continues as long as $countdown is greater than 0.
  5. Once we hit zero, we blast off!

Output:

T-minus 5...
T-minus 4...
T-minus 3...
T-minus 2...
T-minus 1...
Blast off! ?

Traverse a String in Reverse Order

Let's get creative and reverse a string using a do...while loop:

<?php
$str = "Hello, World!";
$length = strlen($str) - 1;

do {
    echo $str[$length];
    $length--;
} while ($length >= 0);
?>

What's happening here?

  1. We start with a string "Hello, World!".
  2. We get the last index of the string (length - 1).
  3. The loop prints each character starting from the end.
  4. We decrement the index in each iteration.
  5. The loop continues until we've printed the first character.

Output:

!dlroW ,olleH

Nested "do...while" Loops

Finally, let's explore nested do...while loops with a fun pattern:

<?php
$i = 1;
do {
    $j = 1;
    do {
        echo "* ";
        $j++;
    } while ($j <= $i);
    echo "<br>";
    $i++;
} while ($i <= 5);
?>

Let's break this down:

  1. The outer loop controls the number of rows (5 in this case).
  2. The inner loop prints stars in each row.
  3. The number of stars in each row equals the row number.
  4. We use <br> to move to the next line after each row.

Output:

* 
* * 
* * * 
* * * * 
* * * * *

Methods Table

Here's a table summarizing the methods we've used in our examples:

Method Description
echo Outputs one or more strings
readline Reads a line from user input
fopen Opens a file or URL
fgets Gets a line from file pointer
fclose Closes an open file pointer
strlen Returns the length of a string

And there you have it, folks! We've looped through the ins and outs of PHP's do...while loop. Remember, practice makes perfect, so keep coding and experimenting with these loops. Before you know it, you'll be looping circles around your coding challenges! Happy coding! ??

Credits: Image by storyset