Introduction to PHP – Getting to Know Arrays Part 2

Guest Posts Paolo Nikko Nuñal

In our last example we showed you how to create an array in PHP and displaying each content of the array by calling their index. This time around you are going to learn how to loop through the contents of an array. To loop through an array you can do this by using the for loop.

Looping through an array can be done in various ways using the for loop but you need to know the size of the array. Luckily, there is a function called count() that makes your work much easier.

For example:

<?php
   $arrayNames = array("Joseph","John","Jane");

for($i=0; $i< count($arrayNames); $i++)
    {
          echo $arrayNames[$i].",";
    }
?>


From the example above, we have encased the array inside the count() method. What it will do is to return the size of the array and loop through until the certain condition returns false, in which it will break the for loop.

Another way to loop through an array is using the foreach loop. This is as simple as the for loop without you having to use the count. You can do this below:

<?php
   $arrayNames = array("Joseph","John","Jane");

   foreach($arrayNames as $value)
    {
          echo $value;
    } 
?>


From the example above we have managed to loop through the array without having to worry much about conditions. All we did was declare the foreach, and use the $value variable to display all elements of the array and use as a reference.