Starting PHP: Looping Basics
Filed under PHP
I was searching the internet for PHP tutorials and quickly found out that the majority of are badly written, have errors in the example code, contain security holes, or are just outright outdated. This makes learning PHP hard for someone just starting out. The question I get a lot is about looping through arrays.
The following are the three possible ways to loop through data, with an example showing how I use them.
The While Loop
The while loop is useful when running loop on data with an unknown size; a database result for example. here’s an example:
<?php
$sql = "SELECT `userid` FROM `users`";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
echo $row['userid'].'<br/>';
}
?>
The above example will continue to check $row to see if it returns false. Each call to mysql_fetch_array() will increment the key. If you ran mysql_fetch_array() outside of the loop, you would get a full array of all the results at once. For example:
Array(
0 => Array( 'userid' => 1),
1 => Array( 'userid' => 2)
)
In this case, you could simply call $row[0]['userid']. But again you don’t know how many results there are so hand coding all the different keys would be just silly.
The For Loop
Just like a while loop, a for loop runs until the expression returns false. Example:
<?php
$array = array('copper','gold','silver');
for($i=0;$i<count($array);$i++)
{
echo $array[$i].'<br/>';
}
?>
For loops are probably the hardest types of loops for php beginners to grasp. The reason behind that is because of the expression used to keep the loop running. So what does $i=0;$i<count($array);$i++ mean? When the loop is first started, the variable $i is set to 0, which happens to be the first key in the $array variable. Next, it checks if the $i variable is less than the total number of items in the array. If the count is greater than $i, the loop continues. Lastly, $i is incremented after one each loop. So after the first run, $i becomes 1, rather than 0.
We have 3 items in the array, so in english, that loop would look like:
i is zero.
if i less than three continue, otherwise break the loop.
add one to i.
The $i variable is accessible anywhere in the loop. It may seem that $i is incremented before any code in the loop is processed, but in reality, it is incremented after the code has been executed.
For loops are also extremely fast for small sets of data. Just keep that in mind if all you have to do are small loops and getting the length of an array or number is no issue.
The Foreach Loop
This last method of looping is my favorite; mostly because it’s easy to follow. Take for example:
<?php
$array = array('bob','joe','billy','rob');
foreach($array as $key => $value)
{
echo $key.': '.$value.'<br/>';
}
?>
This will output:
0: bob
1: joe
2: billy
3: rob
The foreach loop takes each item in the array starting from the left and assigns it a key, or unique number; starting from 0. This is always the case. However, you can choose not to get the key of the current array item by not using the $key part of the foreach loop. Instead, the loop would look like:
$array = array('bob','joe','billy','rob');
foreach($array as $value)
{
echo $value.'<br/>';
}
Now that you read this, the only way to make it stick is to put it to practice. If you need help trying to make something, here’s a script you should try to make on your own:
Make an array of your favorite movies.
Each movie should contain the top 5 or more actors.
Make the script loop through and output each movie and the first three
actors, omitting any others.
If you need a little kickstart here you go:
<?php
$movies = array(
array('The Matrix',
array('Keanu Reeves',
'Laurence Fishburne',
'Carrie-Anne Moss',
'Hugo Weaving
)
)
);
Yes, you will need to nest the loops. I’m sure you can figure it out. Once you get this, I have a good feeling everything else will be a breeze.
August 18th, 2008 at 9:18 pm
Thanks Mal. I’ll be looking into this next week, when I have time.
:]