Let me show you another variant of the while loop.
This time it can be called do while and.
The difference between this while loop that we've seen previously is that in the case of the do while
loop, the statements, the loop body is always executed at least once and only repeated if the expression
returns true.
So that's the main difference with the while loop.
The expression needs to be true first for the body to run with the do while loop.
The body runs first once and is repeated.
If this condition, the expression in the condition returns true.
Let's see a fun example.
So first let's create a new file.
Let's call it do while PHP and open it immediately add a PHP tag.
So as an example we're going to create a simple dice roll game.
So let's begin with the syntax.
It starts with this do keyword followed by the curly braces.
And that's the loop body.
And the condition goes after this last curly brace.
And only then you write while and here goes the condition the expression okay so dice roll game.
We need to pick a random number.
So let me define a dice roll variable inside.
So again I'm going to use a function I know I haven't explained that yet, but without using some of
the things explained in the future, those examples would be pretty dull.
So you just need to bear with me.
This code right here basically picks a random number between 1 and 6.
Okay.
Um, so we need to tell the user what's his role.
So you rolled a and we can also immediately just output this variable inside double quotes.
Add a new line character.
Okay.
So at this point we know what's our role.
If someone rolls six.
Remember about using the value on the left side of comparison to be super safe.
Like that.
We say congrats, you hit the jackpot.
Okay, new line and let's add some celebration icon.
Maybe this.
All right.
Semicolon.
And what's next?
Next we need to ask if the guy wants to roll again.
So we ask a question.
Roll again.
And the answers we accept is yes or no.
So it needs to be lowercase.
And then let's add another variable.
And again here we're going to get the input from the user.
So you've seen that in previous examples.
So there are some function calls like trim to remove the white spaces.
And f gets with SD in to just accept some console input.
And now the condition.
So we only want this to run again if.
Y equals roll again Let's go through this loop again.
The code.
The loop body will always run at least once, so we roll.
We display the result.
We say if someone hit a jackpot and we ask if he wants to roll again.
Now to this roll again.
We just take the user input from the command line and if he typed y then we let him roll again.
So this body will run again, and the guy will be asked for the subsequent rolls until he quits.
So let's save the changes and let's run it.
So this is do while.
PHP.
Okay, so I rolled one.
Let's try again.
There is the jackpot.
And if I choose no or basically any other character, to be honest, the game just quits.