Looping Statements With PHP5.3
by Marc Plotz
August 18, 2009
|
Are looping statements driving you around the bend? Allow
Marc Plotz to straighten the road for you.
|
Introduction
Looping statements are the backbone of PHP. I use them on a
daily basis and they make things really simple. But I always
think back to the days when everything except the WHILE loop
looked alien to me and I wonder if anyone else feels the
same? Do you wonder what those annoying looking $i variables
are doing in that FOR loop? Or what's that funny arrow in
the FOREACH loop? It all really is much more simple than you
think. Let's have a look.
WHILE
This is probably the most simple of all loops, and pretty
much does what its name implies. The loop will iterate WHILE
a statement is true. In other words, while a certain
condition is met, it will continue running through a loop.
What actually happens here is that the condition is checked
and if it comes back true the rest of the code in the
statement is run. Lets have a look at an example:
$query = mysql_query("SELECT * FROM TABLE");
if($query)
{
while($result = mysql_fetch_array($query))
{
echo $result['fieldname'];
echo '<br />';
}
}
What the above will do is loop through the table for as long
as there is a result, or in other words another row in the
database. This is a very simple looping statement, but in
simplicity lies danger: this little exercise, when running
through large database sets can be extremely heavy on
resources. Most of those resources are wasted in the
mysql_fetch_array that is reiterated on every loop of the
statement.
FOREACH
FOREACH is similar to WHILE, except for a few
things. Have a look at the example below:
foreach($array as $key => $value)
{
echo $key.' '.$value;
echo '<br />';
}
What we see above is a statement that basically says: For
each element of the $array associative array I want to refer
to the key as $key and the value as $value. The operator =>
refers to the relationship between the value and the key. I
like to think of it as the key pointing to its value.
Another, more simple way of running this statement actually
ignores the key and simply works with the values as an
array. We explore this below:
foreach($products as $product)
{
echo $product['name'];
echo '<br />';
}
The real simplicity in the for loop is that it
is lighter on resources, it is not checking whether a
condition is true or false, it is not deciding what to do.
Server resources are extremely important, specially when you
are running enterprise class applications. Of course,
something like that will naturally have its own database or
display classes to deal with these types of things. However,
somebody had to write those classes, right? And at the end
of the day it all comes back to what we are talking about
here: whether you are working on Joomla, Zend Framework,
Magenta, or a custom-built framework - when you strip the
code down to the bone what remains is just normal, simple,
boring, every-day statements, switches and, yes, looping
statements. Getting used to these things now will make you a
better coder by far, fast! Anyway, back to the code!
FOR
This was the one that I took the longest to understand. BUT,
now that I understand it, this is the looping statement I
use the most. Mostly due to its flexibility. An example
below explains:
$count = count($array)
for($i=0; $i < $count; $i++;)
{
echo $array[$i]['name'];
echo '<br />';
}
What we are basically saying in the first row is that we
begin at the first key in the array ($i=0) and while $i has
a value less than the amount of rows in the array ($i >=
$count;) keep iterating through the loop ($i++). So, for
every iteration of the statement where $i is lower than the
total amount of rows in the array we shift the value of $i
up one and continue looping. Obviously, when there are no
more rows in the array we need to stop.
There are a few interesting things to note with the
for loop. The first is that I executed the
count of the array outside of the statement. This is
important. Wherever possible, do not put queries, counts,
statements or even more loops inside a looping statement.
Imagine getting hundreds of thousands of entries from a
database. Now imagine that for every entry you count how
many entries there are. I'm guessing you are going to get
old waiting for that query to execute. Executing what only
needs to be executed once outside the loop is good practice.
Once a variable has a value it doesn't need to recalculate it
for every loop, the variable value is set for that entire
script run and is just referenced as need be.
Something else to look at is the part that says ($i <
$count;). What this is looking for is if the $i variable or
counter has a value less than the count of entries in the
array. But, you may ask, shouldn't it be executing while the
counter has a value less than or equal to the count of array
entries? Well. That is exactly what is happening, it just
does not look that way at first glance. What you need to
remember is that the array counter starts at 0, not one, in
this instance. Now imagine there are 52 entries in the
array. Thus, $i reaching 51 will actually be the 52nd entry,
since the count started at 0 and not 1. Therefore only
executing while the counter is less than 52 means that the
counter will execute 52 times but have a value of 51 on its
final iteration.
Conclusion
Looping statements are the backbone of PHP code. We use it
daily, looping through lists, arrays, database entries and
such. Understanding them is more important than just about
anything else in PHP. It means nothing that you can get the
data out of the database if you can do nothing with it at
the end of the day. Therefore I have briefly touched on the
simple workings of the three most popular looping
statements, showing you simple examples of how they work and
why they look like they do.
As always, happy LOOPING!
|