PHP Loops (do-while) 🎯

beginner
6 min

PHP Loops (do-while) 🎯

Welcome back to CodeYourCraft! Today, we're diving into the world of loops with a focus on the do-while loop in PHP. Let's get started!

What is a Loop? πŸ“

In programming, a loop is a control structure that allows us to repeat a specific block of code as many times as needed. Loops are incredibly useful when dealing with repetitive tasks.

Introducing the do-while Loop πŸ’‘

The do-while loop is a type of control structure that checks the condition at the bottom of the loop. This means that the loop will always run at least once, even if the condition is initially false.

Here's the basic structure of a do-while loop in PHP:

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

Example: Counting Numbers 🎯

Let's create a simple example where we count numbers from 1 to 10 using a do-while loop.

php
$count = 1; do { echo $count . "\n"; $count++; } while ($count <= 10);

In this example, we start by initializing a variable $count to 1. We then enter the do-while loop. Inside the loop, we print the value of $count, increment it by 1, and check if it's still less than or equal to 10. If so, the loop continues; if not, it ends.

Advanced Example: User Authentication πŸ’‘

Now let's make our do-while loop a bit more practical by using it for user authentication. In this example, we'll ask the user for a password, and the loop will continue until the correct password is entered.

php
$password = "secret"; $input; do { echo "Enter your password: "; $input = trim(fgets(STDIN)); if ($input === $password) { echo "Correct password!\n"; break; } else { echo "Incorrect password. Try again.\n"; } } while (true);

In this example, we start by setting a secret password. We then enter the do-while loop, where we continuously ask the user for a password and check if it matches the secret password. If it does, we print "Correct password!" and break out of the loop. If it doesn't, we print "Incorrect password. Try again."

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is a loop in programming?

Quick Quiz
Question 1 of 1

What does the do-while loop check before entering the loop body?

That's it for today! With these examples, you should have a good understanding of the do-while loop in PHP. Keep practicing, and remember to check back for more tutorials at CodeYourCraft! πŸš€

  • The CodeYourCraft Team πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»