My PHP journey part 3.


Today we’re going to learn about loops. I’ll be honest, It’s taken me about a week and a half to understand what loops are and what they do.

When my tutor introduced the subject by saying something on the lines of “Hooray! Today we’re doing loops!”

I was I felt an hooray – instead I felt like my head was going to explode. And what was worst is that I think the rest of the class managed to grasp it.

Anyway.. onwards and upwards…

The While Loop

Apparently, this is the simplest type of loop.

It looks like this…

while ( condition ) {
code to run

If the condition evaluates to true then the code (the bit in curly brackets) will run.

A simple example we used in class was counting to ten.

$i = 1; //The value of $i… simple enough so far

while ($i <= 10) { //While $i is less than or equal 10…which it is… we’ve already defined it..
echo “$i”; //show $i from now on…
$i++; //Now, we’re adding an increment to $i

} //Close curly brackets.

Remember, you won’t see any number higher than 10, because you’ve told it not to count that high using the <= symbol. Less than or equal to.

The Do While Loop

It looks like this..

do {
code to run at least once
while ( condition );

The bit in the ‘do’ brackets is run before the condition is evaluated.

For example

$i = 10; //$i is 10… simple enough
do {
echo $i; //Show me 10..
} while ($i < 10); //Now you’ll just see 10…

I’m not sure of the point of this one, hopefully the penny will drop soon.

The For Loop

This looks like the most useful, but the most difficult to comprehend…

It looks like this.

for ( expression1; expression3; expression4 ) {
code to run

Expression 1 – This is only looked at once, so it sets the initial values, for example $i = 10;

Expression 2 – This is evaluated before the code and a boolean, it’ll be either true or false

Expression 3 – This is executed at the end of the loop and can change the value of expression 1… Creating the said loop.

For example

for ($i = 1; $i <= 10; $i++) {
echo $i;

So… $i equals 1. If $i is less than or equal to 10… Add another figure next to $i… Counting to 10.

If the middle expression evaluates to true then you’ll see something. In the case above, you’ll see the counter from 1 to 10.

Leave a Reply

Your email address will not be published. Required fields are marked *