PHP Lessons 5: Loops

by
Guest-GS

Loooooops!

In this lesson, we will have a look at the foreach function in php.

First, what is a loop? I’d say something that repeats or involves a repetition can be considered a loop. In programming, you use a loop to have a bunch of codes run for a number you set. If there were no loops, you’d have to write that piece of code x times if you wanted to run it for x times, which is crazy! Read on to know the solution!

For example, I could tell PHP to give me 5 “Hello, World!” like this:

<?php

  echo "Hello, World!";
  echo "Hello, World!";
  echo "Hello, World!";
  echo "Hello, World!";
  echo "Hello, World!";

?>

5 is ok. What if I wanted 10,000 “Hello, Worlds”? Happy copy-pasting! But no, that’s where loops come useful. I could just tell PHP:

<?php

  do what follows 10,000 times:
      echo "Hello, World";

?>

That’s what a loop is. Well the line “do what follows” is not a PHP command! We’ll see the real syntax soon. Just remember this “Hello, World example” since we’ll use it below for illustration.

There are 4 types of loops which are mostly used:

1. The While loop
2. The Do While loop
3. The For loop
4. The Foreach loop

The While loop

Let’s see how we could do 5 Hello World with a While loop:

<?php

  $i = 0; //initializing our counter

  while ($i < 5){

      echo "Hello, World";

      $i++; //Incrementing count
  }

?>

Not that tough is it? And definitely much smaller than the one above. For 10,000? Just replace: while ($i < 10000). The rest is the same. It’ll run for 10,000 times! That’s how you do a While loop. Let’s analyse the code.

Loops need a counter variable, which we programmers like naming i, j, x, y or your favourite single letter. Usually, we start at i and move on. i is like a non-standard convention that programmers use, which says that the var is a loop counter.

Then, we do the While part. Notice that I used $i < 5 and not $i <= 5. It’s so because I started the count at zero, which is the usual way. If you start the counter at one, then it will be $i <= 5; But start with zero. It’s more often used. So, $i < 5. The While loop will check the value of $i everytime the loop runs. It’d go like this:

Value of $i is less than 5? ($i = 0) Yep, so run loop. Increment $i. ($i = 1)
Value of $i is less than 5? ($i = 1) Yes, so run loop. Increment $i. ($i = 2)
Value of $i is less than 5? ($i = 2) Ya,  so run loop. Increment $i. ($i = 3)
Value of $i is less than 5? ($i = 3) Yay, so run loop. Increment $i. ($i = 4)
Value of $i is less than 5? ($i = 4) Yey, so run loop. Increment $i. ($i = 5)
Value of $i is less than 5? ($i = 5) NO! ($i < 5) returns false. End the loop!

So you see the loop made 5 runs.

For a While loop, you should absolutely NOT FORGET the Increment Your Count part. This is vital! What happens if you miss that line? You get an Infinite Loop, or a loop that never ends. Or simply, an awful massively huge lot of “Hello, World!” and your code crashes.

The Do While loop

The Do While loop is just a reverse While. If you read the code from the previous section carefully, you will see that the While loop makes the variable /counter check at the start of the loop. In a Do While loop, we make the check AFTER the loop.

What does this change? The While loop code above wouldn’t run if I had initialized the counter to $i = 10; PHP would just have skipped the loop and process the code after it if any, since $i is not less than 5.

But if I had done it with the Do While loop:

<?php

  $i = 0; //initializing our counter

  do{
      echo "Hello, World";

      $i++; //Incrementing count

  }while ($i < 5);
?>

That code would have ran for at LEAST one time, so even if I had initialized $i = 10; there would be ONE “Hello, World” that gets output. Of course, if $i is zero at the start, you’d get your 5 “Hello, World” normally, as the While loop.

So how is this change useful? In some situations, you might want to run a check, then decide to see how many times to run the loop, if ever you want to run it. It is in those situations that the Do While is important.

Important thing to notice is the structure of the Do While loop itself. There is NO semicolon after the “do” keyword. The semicolon comes AFTER the “while ($i < 5)” condition check. Again, don’t miss that semicolon (or any of them, for that matter). Your code won’t run.

The For Loop

The For Loop is just like a classic While loop, but it includes the initialization, check and incrementation/decrementation directly in its declaration. Yep, you might want to decrement a count instead of incrementing it. Why? That’s what you’d do if you wanted to echo something in reverse. Start the counter at the last position, and decrement to the start.

Back to the For loop:

<?php

  for ($i=0; $i<5; $i++){

      echo "Hello, World";
  }
?>

That’s how your For loop looks like, and it will give you your 5 “Hello, World” as above. You can notice how concise it is. Let’s analyse it.

for ($i=0; $i<5; $i++) The first part/parameter is the initialization. Next comes the condition. Finally the incrementing. Note those semicolons. They are NOT commas. This is a common mistake among beginners.

The Foreach loop

The Foreach loop is specially designed to work with Arrays (read our lesson on Arrays if you haven’t done so yet). As you probably know by now, Arrays are just consecutive storage spaces, like a set of variables. Sometimes, you might want to do something about all the data in the array, like echoing the data in each slot. Or maybe, some selective slot? Maybe check for some value? All those are done via the Foreach loop.

Basically, the Foreach is in fact “foreach slot in an array, do those codes”. The Foreach loop in PHP4 works ONLY on arrays by the way. PHP5 can iterate over visible values in classes too. Classes and Object-Oriented Programming come further away in the series.

An example, this time coming from the Arrays lesson. To output the values we have, we would just echo $name[0],$name[1] and so on.

<?php

  $persons = array('John','Richard','Max','Michael');

  echo $name[0]; // outputs john
  echo $name[1]; // outputs Richard
  echo $name[2]; // outputs Max
  echo $name[3]; // outputs Michael

?>

But, what if the data are coming from a database and you have around 100 values? WTF, does that mean we should keep echoing $name[0] to $name[99]? No way, that’s pointless and it will tax the server. So, the Foreach loop will come in handy in this kind of situation.

How do we write a foreach? Below is the general syntax:

<?php

  foreach($our_array as $the_value){

      //keep doing what you're told to with the values

  }

?>

Let’s iterate through our arrays with the foreach loop:

<?php

  $persons = array('John','Richard','Max','Michael');

  foreach($persons as $value){

      echo $value.'<br />';

  }

?>

What it means in the code above is, foreach item in the array (the array is $persons), copy it to the $value variable, then between the curly braces, output every value you got. The output will be like this:

John
Richard
Max
Michael

As you can see, with this simple foreach, we were able to output the four names in our array without having to echo every items in the array. That’s much better and also, this simple code will also output 100 values if they were in the array.

A little note: Some of you might be wandering why is there a ‘<br />’ at the end. If you know some HTML (Which I suppose you know a bit of. To really use PHP well, you need to have a basic HTML knowledge), then the <br /> tag will simply insert a simple break line. What I did in the code above is simply concatenated the HTML BR (BReak) tag to the end of the variable by using the period sign (the dot if you prefer), and then adding the <br /> tag between single quotes and end the statement with the semicolon.

Ok, this give us an idea our the foreach loop, but what if my array contains a KEY for every VALUE, as in Associative Arrays? The answer is: You can still use the foreach loop to get the both the KEY and the VALUE in your array. The  general syntax is below:

  foreach($our_array as $the_key => $the_value){
      //do your stuff here
  }

Have a look at “the_key => the_value” . It looks the same way we write our associative array like below. ‘John’ => ’18’, John is the Key, 18 is the Value. Let’s use the foreach with it.

<?php

  $persons = array('John' => '18',
                   'Richard' => '20',
                   'Max' => '25',
                   'Michael' => '30'
                  );

  foreach($persons as $key => $value){
      echo $key.': ' .$value. '<br />'
  }

?>

So remember, John, Richard, Max and Michael are Ks. We assign the Kry to the variable $key and the value to the variable $value. So you basically get an idea of how the output will be. It will be like below”

John: 18
Richard: 20
Max: 25
Michael: 30

So if you want to make a sentence with it. say: John is 18 years old. You would do like so:

<?php

  $persons = array('John' => '18',
                   'Richard' => '20',
                   'Max' => '25',
                   'Michael' => '30'
                  );

  foreach($persons as $key => $value){
      echo $key.' is ' .$value. ' years old.<br />';
  }

?>

This will output:

John is 18 years old.
Richard is 20 years old.
Max is 25 years old.
Michael is 30 years old.

See those concatenations? That’s how we add static stuff and variables together. Add necessary spaces inside quotes too, else you will just have a bunch of unreadable lines like “Johnis18yearsold.”

You see how the foreach loop makes life easier. Instead of having to echo those one by one, we were able to do it with three lines of code.

Let’s see another example, using a For loop and a Foreach loop to do the same job.

Using a For loop first:

<?php

  $persons = array(array('name' => 'John', 'gender' => 'male'),
                   array('name' => 'Anna', 'gender' => 'female')
                  );

  for($i=0; $i<count($persons); $i++){
      echo $persons[$i]['name'].'<br />';
  }

?>

Like you see in the code above, we have our Multidimensional Array. Our For loop is pretty much the same except that you can see a little built-in function called count. What this function does, it calculate the size of the array everytime it runs through. We’ll see about Functions in a future lesson. Note, you may also see code which uses sizeof function like: $i < sizeof($persons). Don’t worry, sizeof and count are the same thing. sizeof is an alias of count. Also, if you wanted to know how the length (or number of elements) a Multidimensional array contains, you can use: count ($persons, COUNT_RECURSIVE) function. COUNT_RECURSIVE is a constant with value 1, and is an optional parameter.

When echoing out, we use the $persons variable, we use [$i] ($i would just contain the Numeric Value of our array. Remember from the array lessons? The Numeric Array?). After passing in $i, we pass in the KEY, which is ‘name’! So if we didn’t use the For loop, we would have to echo our values like below:

echo $persons[0][‘name’]; // will write John
echo $persons[1][‘name’]; // will write Max

Why didn’t we just write $persons[‘name’] ? Simply because we are using a MultiDimensional Array and we have to get to the first array inside of that Main/Parent array and so on. When using the For loop, we don’t have to specify the number ‘0’ and ‘1’, since it is stored in $i which makes our work easier by echoing using only one line of code, and it would echo every name we have in the array. Very nice for large arrays.

Let’s see how we can do it with a Foreach loop. If you prefer to use the foreach loop to iterate through this example, it would look a bit different from what we wrote before. We would have to use our Foreach to loop in the main Array, then use another Foreach loop to get the arrays inside. This is called Nested Foreach Loop. Here’s an example below:

<?php

$persons = array(array('name' => 'John'),
                 array('name' => 'Max')
                );

  foreach($persons as $value){
      foreach($value as $values){

          echo $values.'<br />';

      }

  }

?>

I know this can confuse you, but really, it’s quite simple. Let’s break it down. Have a look at our array, it contains two arrays, one in another.

Our first foreach will iterate through the Main array and gives us the arrays we have inside and store them in the variable $value. (we are still in the first Foreach loop – the “outer” one).

Since the variable $value contains the two arrays inside the main one, we have to use another Foreach loop to iterate through those arrays.

So our second Foreach loop (“inner” one), which is inside the first foreach loop, will take the variable $value which contains the two arrays, copy it to the variable $values in each loop, then we can start outputting the name we have inside of it.

Still confused? You almost should be, if you are a beginner. Just try to re-read and understand. If you have questions, use the comments form below. We try to answer questions, but are not pro’s, so we might not know everything.

Hopefully, by now, you understand how to use Array, how to iterate through them using either foreach and for loop.. Understand how to use a Foreach loop and how to use a For loop. Using those will make your life easier trust me. Why bother with 4 kinds of loops? Each has its use, but in most situations, the For and Foreach loops are the one you’d want. While loop is specially useful where you don’t know exactly how many times to loop or need to do something special, instead of blindly incrementing the count. More of this to come soon. 🙂

Try to see what those functions do on your own and how to use them:

is_array() – checks to see if a variable is an array
in_array() – checks to see if a value is found in an array
explode()  – turns a string, separated by delimiters into an array
implode()  – reverse of explode. Array to string this time

You might want to have a look at those since later we will be using them in a tutorial where data will be coming from a MySQL database.

Also, remember to install WAMP or XAMP and try out those simple example for yourself just to adapt yourself with the syntax. Practice is better than just reading and trying to understand what’s happening. And if you see any syntax errors or whatever, let us know. Thanks!

P.S: If I’m not mistaken, I believe till now this is the longest tutorial I wrote. 😀

This article was contributed by Tipa of Mu-Anime

[seriesposts title=”PHP Lessons” titletag=h3 listtype=ul orderby=date name=”PHP Lessons” ]