The for loop in PHP

The for loop in PHP

11/05/2023
78 Lượt xem

So we have learned two important control statements in PHP, which are switch case and if else statements. In this article, we will start exploring a new concept, which is loops, and specifically the for loop in PHP.

The content includes:

  • What is a loop?
  • The for loop
  • Nested for loop
  • Using for loop to process arrays

1. What is a loop?

A loop is a code structure where the program is executed repeatedly until a certain condition is met. Loops are a fundamental concept in structured programming.

In PHP, there are several types of loops:

  • For loop
  • While loop and do-while loop
  • Foreach loop

2. For loop

Syntax:

<?php
	for ($control_variable; $condition_expression; $control_expression){
		// statements
	}
?>

In which:

  • $control_variable: is an assignment statement that assigns an initial value to the control variable before executing the loop, or a variable with a pre-assigned value passed to the loop creation, this statement is only executed once.
  • $condition_expression: is a relational expression that determines the condition for exiting the loop.
  • $control_expression: determines how the control variable will be changed after each iteration (usually by increasing or decreasing the value of the control variable).

The above three expressions are separated by semicolons. The loop will continue to iterate as long as the condition expression is true, and it will stop and exit when the condition expression is false. We use relational and logical operators in condition expressions to control the loop.

Consider the following example:

<?php
	for ($i = 0; $i < 10; $i++){
	    echo $i . ' - ';
	}
?>
  • $i = 0 is the control variable initialized to 0.
  • $i < 10 is the condition that stops the loop, meaning if $i < 10, the loop continues, otherwise if $i >= 10, the condition is false, and the loop will exit.
  • $i++ is the expression that changes the control variable, after each iteration $i will be incremented by 1.

Loop iteration 1: $i = 0, the condition expression will be (0 < 10) => true => the loop is executed and outputs the string “0 -“. After all the commands inside the loop are executed, the change condition expression is performed so $i will be increased by 1, now $i = 1.

Loop iteration 2: $i = 1, the condition expression will be (1 < 10) => true => the loop is executed and outputs the string “1 -“. Combined with the string in the first loop, the screen will display the string “0 – 1 -“. After all the commands inside the loop are executed, the change condition expression is performed so $i will be increased by 1, now $i = 2.

Similarly for loop iterations 3, 4, 5, 6, 7, 8, 9.

Loop iteration 10: $i = 10, the condition expression will be (10 < 10) => false => the loop ends. At this point, the variable $i will remain unchanged and will not be incremented anymore, so it retains the value 10.

End: The screen outputs the string “0 – 1 – 2 – 3 – 4 – 5 – 6 – 7 – 8 – 9 – “.

For the above example, we can rewrite it as follows and the return result will be the same, only different in that the variable $i is assigned a value outside the loop.

<?php
	$i = 0;
	for ($i; $i < 10; $i++){
	    echo $i . ' - ';
	}
?>

In the example above, the control variable is incremented. In the following example, the control variable will be decremented, and the result will print in reverse order: “9 – 8 – 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 -“.

<?php
	for ($i = 9; $i >= 0; $i--){
	    echo $i . ' - ';
	}
?>

Inside the loop body, we can add more expressions by using commas to separate them.

Example:

<?php
	for ($i = 9, $count = 10; $i <= $count; $i--){
	    echo $i . ' - ';
	}
?>

3. Nested for loops

Like the if condition, the for loop in PHP can be nested to handle complex problems. In each parent loop, the child loop will be executed (the child loop will loop until finished), following the rule that the content inside the loop must be completed before executing the next loop.

Example:

<?php
	for ($i = 1; $i < 10; $i++){
	    for ($j = 9; $j >= $i; $j--){
	        echo $j;
	    }
		echo '<br/>';;
	}
?>

This problem prints a triangle to the screen:

987654321
98765432
9876543
987654
98765
9876
987
98
9

The total number of iterations is equal to the product of the number of iterations of the two nested loops plus the number of iterations of the outer loop. For example, if the first loop iterates 10 times and the second loop iterates 10 times, then the total number of iterations will be 10 x 10 + 10 = 110 times. Therefore, the cost of using nested for loops is very high.

4. For loop combined with array

From the example above, we can see that the for loop in PHP iterates in a consistent increasing or decreasing order, which is similar to the indices of an array. Therefore, we can conclude that we can use a for loop to access each element of an array.

Example: Given an array of students:

<?php
	$students = array(
	    "John",
	    "Jane",
	    "Mark",
	);
?>

Output the students in the array to the screen?

Method 1: Output each element based on the index.

<?php
	echo $students[0];
	echo $students[1];
	echo $students[2];
?>

Method 2: Use a for loop.

<?php
	for ($i = 0; $i < 6; $i++){
	    echo $students[$i];
	}
?>

Looking at the solution, do you know why the index starts at 0? It’s because in an array, the first element has the position number 0, and the last element has the position (n-1). Here, n is the total number of elements.

With the second method, we can slightly modify it by using the count() function to count the total number of elements and loop through the array. This way, no matter how many elements there are in the student array, the code won’t be affected. If we don’t do this and let’s say we reduce the student list to only 3 students, then the second method will raise an error, while the modified method will still work without errors.

Modified method 2:

<?php
	for ($i = 0; $i < count($students); $i++){
	    echo $students[$i];
	}
?>

In terms of optimization, this method is still not optimal because we put the count() function inside the loop body, which means it will count the total number of elements in the array every time it loops through the array. If the array has 10 elements, it will count 10 times, and if it has 20 elements, it will count 20 times. In reality, we only need to count once, so the following method will be more optimized.

<?php
	$count = count($students);
	for ($i = 0; $i < $count; $i++){
	    echo $students[$i];
	}
?>

For a 2D array, we have to use a nested loop to handle it. This issue will be discussed in the next lesson on handling arrays in PHP.

5. Conclusion:

In this lesson, you have learned about the for loop in PHP, a very commonly used loop in programming languages. In reality, loops are used a lot, so you must master them in order to choose the most suitable one. In the next lesson, we will study the while and do-while loops.

5/5 - (2 votes)
Download and Install Vertrigo Server
11/05/2023
78 Lượt xem
Operators and expressions in PHP
11/05/2023
78 Lượt xem
The if else statement in PHP
11/05/2023
78 Lượt xem
The switch case statement in PHP
11/05/2023
78 Lượt xem
The for loop in PHP
11/05/2023
78 Lượt xem
While and do-while loops in PHP
11/05/2023
78 Lượt xem
The foreach Loop in PHP
11/05/2023
78 Lượt xem
Building Functions in PHP
11/05/2023
78 Lượt xem
Recursive Algorithm in PHP
11/05/2023
78 Lượt xem
Bubble Sort Algorithm in PHP
11/05/2023
78 Lượt xem
Linear Search Algorithm in PHP
11/05/2023
78 Lượt xem
The technique of sentry placement in PHP
11/05/2023
78 Lượt xem
Flagging technique in PHP
11/05/2023
78 Lượt xem
Selection Sort Algorithm in PHP
11/05/2023
78 Lượt xem

Related Articales

Comments

© copyright 2021 Courseplus