Understanding For Loop in PHP

Hi… today we’ll discuss popularly and frequently used (including myself) loop: for loop in PHP.

PHP provides three loops: while, do-while, and for. The difference between the while, do-while, and for that is for for loop, the number of repetitions are already known, while for the while and do-while loop are not.

For Loop In PHP

I. Syntax For – For Loop In PHP

In PHP, a for loop can be written using curly brackets, colon, and without both:

// Using Curly Brackets
for ( expression1 ; expression2 ; expression3 ) { 
	// Code - Statement Block
}

// Using Colon
for ( expression1 ; expression2 ; expression3 ):
	// Code - Statement Block
endfor;

// Without Curly Brackets or Colon
for ( expression1 ; expression2 ; expression3 )
	statement;

While running a for loop function, PHP will execute script in the following order:

  1. PHP will first read expression1.
  2. Furthermore, PHP will evaluate expression2, if evaluated to TRUE, then the statement in the brackets will be executed, otherwise the loop will be terminated.
  3. Then PHP will evaluate or run expression3

and so on until the loop is complete.

Some rules for writing the expressions

There are some rule and options that we can use while writing the expressions:

  1. All expressions are allowed not to be written (empty) or could contain more than one expression which separated by a comma ( , )
  2. All expressions in expression2 will be evaluated, but for determining the TRUE or FALSE value (which will be used to decide whether the loop stops or continues), the LAST expression will be used.
  3. If expression2 is empty, then the loop will run continuously until terminated by a break statement that declared in the statement block.

Here are some examples of writing for loops with different expressions, all of them will print number 1 to 10. The FIRST form is the most common used.

/* 
1st Form, MOST USED
*/

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/*
2nd Form, with expression2 empty, the code terminated with the break statement
*/

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* 
3rd Form, with empty expressions
*/

$i = 1;
for ( ; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* 
4th form, no statement, only expressions
 */

for ($i = 1; $i <= 10; print $i, $i++);

II. Skip for loop at a particular value

While the for loop is running, we may want to skip it at the particular value, to do this, we can use the continue statement, for example:

for ($i = 1; $i <= 10; $i++) {
	if ($i == 5) {
		continue;
	}
    echo $i; // 1 2 3 4 6 7 8 9 10
}

III. The Writing Standards

According to PSR-2 (PHP Standard Recommendation) defined by FIG (Framework Interoperability Group), you should write for loop like the following form:

for ($i = 0; $i < 10; $i++) {
    // for body
}

Explanation:

  • Use braces instead of colon.
  • The statement is written exactly one line underneath the expression.
  • Notice the use of space in the expression, each expression and expression’s value should be separated by a space ( $i == 10; $i < 10, $i++ ), this is for readability purpose.

IV. Some Useful Tips While Writing For Loop in PHP

1 Avoid calling function and defining variables that have STATIC/FIXED value within the loop

This function can be either native PHP functions such as count, substr, strlen, etc. as well as a user-defined function, the following example use loop for displaying the name of the month and get the month of due date:

$duedate = '2016-11-10';
for ($i = 1; $i <= 12; $i++)
{
	$months[$i] = date("F", mktime(0, 0, 0, $i+1, 0, 0));
}
	
echo '<table>
		<tr>
			<th>Month</th>
			<th>Description</th>
		</tr>';
		
	for ($i = 1; $i <= count($months); $i++)
	{	
		$duedate_mon = date("m",strtotime($duedate));
		echo '<tr>
				<td> ' . strtoupper($months[$i]) . ' </td>';
			
		if ($duedate_mon == $i)
			echo '<td>Due Date</td>';
		else
			echo '<td>-</td>';
			
		echo '</tr>';
	}
echo '</table>';

Output:

Month Description
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER Due Date
DECEMBER

From the above example, PHP will:

  1. Call the function: count($months),
  2. Call the function: date("m",strtotime($duedate))
  3. Define the $duedate_mon variable,
  4. Call the function strtoupper($months[$i]).

All of these will be executed 12 times, it is not efficient at all because it will take more times and resources. Therefore, let’s rewrite the loop by defining functions and static variables outside the loop:

$duedate_mon 	= date("m",strtotime($batas_waktu));
$num_month   	= count($months);		
for ($i = 1; $i <= $num_month, $i++)
{
	// code
}

More simple:

$duedate_mon 	= date("m",strtotime($batas_waktu));		
for ($i = 1; $num_month = count($months), $i <= $num_month, $i++)
{
	// code
}
Note: As discussed before, if the second expression contains more than one expression, then the LAST expression is used for defining the TRUE or FALSE value, so the $num_month = count($months) will be executed ONCE and $i <= $num_month will be executed 12 times.
Note2: We couldn’t place the strtoupper($months[$i]) function outside the loop because it’s value is always changed according to the number of the month.

2 Avoid execute SQL Query within the loop

If possible, do not execute SQL query inside the loop, with repeated execution it will hurt the database server and reduces the performance of your application.

Here is an example of MySQL query execution within loop:

$months_num = count($months); 
for ($i = 1; $i <= $months_num, $i++) { 
	$mon	= substr('0'.$i, -2); // 2 digit month
	$sql 	= 'SELECT total_due FROM sales WHERE MONTH(order_date) = $mon; 
	$stmt 	= $pdo->prepare($sql); 
	$stmt->execute(); 
	$sales[$mon] = $stmt->fetchAll(PDO::FETCH_ASSOC); 
}

For optimization, create the SQL query using loop and then executes outside the loop.

3 Be careful while writing the nested loop

Be careful when working with nested loop, especially in naming the expressions variables, because it can be easily overwritten by the “child” loop (loop within loop) variables.

The safe way is giving a variable name that reflects the existing conditions, not just $i or $j, at least it will  prevent the variable from accidentally overwritten. For example, in the following code, I use variables named $row and $col, instead of $i and $j

for ($row = 1; $row <= 5; $row++)
{
    for ($col = 1; $col <= $row; $col++)
    {
        echo '*' . '<br/>';
    }
}

The result:

*
**
***
****
*****

Subscibe Now

Loves articles on webdevzoom.com? join our newsletter to get quality article right to your inbox. Nothing else, just quality stuff!!!

Related Post

Leave a comment

Like Us

Newsletter

Great information from webdevzoom.com right to your inbox

We value your privacy

Social