PHP Loops - Part One

Hello There Pretty Brain ...

In this tutorial we'll be looking at PHP loops.

In particular, we'll be looking at how they can be used to iterate over data, as well as how they can help us execute some piece of code repeatedly until the desired result.

Let's first look at arrays, because understanding them; will help us in the proper comprehension of PHP loops as a programming concept. Well loops are mostly used on arrays, so this will be a very useful exercise.


Okay now that I've drowned your youth in the tales of arrays and their pretty properties, let's finally start talking about those loops shall we?!!

We'll do them in the following order:

We'll show you what they look like, what each does, and then; much later we'll have you writing the code for yourself and testing it out on your machine.

For Loop
    for ($x = 0; $x <= 10; $x++) {
        echo "The number is: $x <br>";

If you have a bit of a problem creating a PHP file with the text editors, and placing it in the correct folders. Please read these tutorials
What is PHP?
Settign up your developemnt Environment

But if you're comfortable creating you own php files in your localhost, then by all means; let's code :)

     * These are comments - they are not part of the code
     * We put these in our files to tell the reader a bit about the code

    // This is also a comment, it's not run
    // Anything after these two slashes is a comment - not run!!
    //$array = array('cape town', 'Durban', 'Johannesburg');
    $array = ['Cape Town', 'Durban', 'Johannesburg'];

    //For Loop Below
    for($i = 0; $i < count($array); ++$i) {
       echo $array[$i]." <br>";


You know the drill soldier ... save, reload, and voila!

"Within the for loop , you can do whatever you want , write what ever you want, do whatever you want to the variables"

The Village Geek

"Alright, alright, alright ..." - Matthew McConaughey

We've learnt a lot in this tutorial; arrays, loops, and programming iterations in general. Please try and play around with this FOR loop and try and modify the variable, values, and arrays when doing so. Also try to change the increment values, starting values and the limits to see what happens.
In the next tutorial, we'll look at the FOREACH loop, the WHILE loop, and the DO WHILE Loop.

Stay you or be better.
Cape Town, South Africa

Buy me a coffee ? :) Buy me a coffee :)

Reply to this discussion


Coming Soon ...