PHP Do While Example

Here is an example of a PHP do-while loop:

<?php
$i = 0;
do {
    echo $i;
    $i++;
} while ($i < 10);
?>

This code will print the numbers from 0 to 9. The difference between a do-while loop and a while loop is that a do-while loop will always execute the body of the loop once, before checking the condition. In this case, the body of the loop will print the value of $i. Then, the condition will be checked, and if it is true, the body of the loop will be executed again. This will continue until the condition is false, which will happen when $i is equal to 10.

Do-while loops can be useful when you want to make sure that the body of the loop is executed at least once, even if the condition is false. For example, you might use a do-while loop to make sure that a user enters a valid value before continuing with a task.

Here is another example of a PHP do-while loop:

<?php
$i = 0;
do {
    // Get the user input
    $input = readline("Enter a number: ");

    // Check if the input is a number
    if (!is_numeric($input)) {
        echo "Please enter a number.\n";
    } else {
        // Break out of the loop
        break;
    }
} while (true);

// If the user entered a number, do something with it
if (is_numeric($input)) {
    // Do something with the input
}
?>

This code will ask the user to enter a number. If the user enters a number, the code will do something with it. If the user does not enter a number, the code will ask them to enter a number again. This will continue until the user enters a valid number.

No comments:

Post a Comment