PHP Loops and Options

PHP Loops and Resources

First of all, not all loops are created equal. When coding in PHP or any other language for that matter, it never hurts to write code that is highly optimized. With PHP, there are so many ways to do things that you will see code written in all sorts of ways. And loops are particularly vulnerable to such unorthodox ways for which they can be written.

Since loops are often written within loops, a multitude of options are available. For example, you may query a database and obtain an array of ids in a while loop. Then, you may want to run another while loop within the while loop to check another table for data where the ids match.

Here are 2 examples for which the output is exactly the same. The first sample uses a single loop to print out data while the second example will make an array of the ids in the first loop, then use that array to find other data in a second loop. As you can see with a timing function called microtime(), example one not only outperforms example 2; it blows it away.

The small time might seem unnoticeable to the eye, but with larger websites, larger traffic and more loops added into the equations; writing optimized code can sure pay dividends. The overall performance will be better since less resources will be consumed. If you want to go big, you will want your queries as optimized as possible.

Example #1

$db=db_connect();
$start = microtime(true);
//$ids_all = array();
$id=array();
$command= 'SELECT id, firstname, age FROM table_sort';
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user_age = $row['age'];
$user_firstname= $row['firstname'];
echo "<h2>Hi id #".$id."</h2>";
echo "Firstname: ".$user_firstname." | Age: ".$user_age."<br/>";
}
$end = microtime(true);
$elapsed_time = number_format($end - $start,4);

echo "Time took $elapsed_time seconds\n";

Example#2

$db=db_connect();
$start = microtime(true);
//$ids_all = array();
$id=array();
$command= 'SELECT id FROM table_sort';
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$ids_all[] = $id;

}

$ids_all = array_unique($ids_all);

foreach($ids_all as $id_user){
echo "<h2>Hi id #".$id_user."</h2>";
$command = "SELECT age, firstname FROM table_sort where id='$id_user' ";
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$user_age = $row['age'];
$user_firstname= $row['firstname'];
echo "Firstname: ".$user_firstname." | Age: ".$user_age."<br/>";
}
}

$end = microtime(true);
$elapsed_time = number_format($end - $start,4);

echo "Time took $elapsed_time seconds\n";