07 Jul PHP Loops
Loops execute a block of code and this code executes while the condition is true. PHP Loops include the while loop, do..while loop, for loop, and the foreach loop.
Let’s learn about PHP loops one by one. Here are the types of loops in PHP,
- while loop
- do…while loop
- for loop
- foreach loop
PHP while Loop
In the while loop, the block of code executes only when the condition is true. It executes as long as the condition is true.
Here’s the syntax:
1 2 3 4 5 |
while (condition is true) { code; } |
Example
We’re running while loop from $a = 0 to $a <5 i.e. 5 iterations. When the value of a reaches 5, the iteration stops, and the value gets printed as shown below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <?php $a = 0; while($a < 5) { echo "Value: $a <br>"; $a++; } ?> </body> </html> |
Here’s the output,
PHP do…while loop
The block of code executes once, then the condition is checked, unlike the while loop. The loop executes, till the condition is true.
Here’s the syntax:
1 2 3 4 5 |
do { code; } while (condition is true); |
Example
The code executes once with $a = 10, then the condition $a < 15 is checked. The loop executes till $a < 15,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <?php $a = 10; do { echo "Value: $a <br>"; $a++; } while ($a < 15); ?> </body> </html> |
Here’s the output,
PHP for loop
It is used when you can set the number of times a statement is to be executed.
Here’s the syntax:
1 2 3 4 5 |
for (initialisation; condition; increment/decrement counter) { code; } |
The above syntax shows the following parameters,
- initialisation- The loop counter value initializes here.
- condition- If the condition is TRUE, the loop continues, else the loop ends.
- increment/decrement counter- Increase/ Decreases loop counter value
Example
Here you can see five iterations from $a = 1 to $a = 5,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <body> <?php for ($a = 1; $a <= 5; $a++) { echo "$a <br>"; } ?> </body> </html> |
Here’s the output,
PHP foreach loop
The foreach loop is used to loop through each key/value pair in an array. That means it only works for arrays.
Here’s the syntax:
1 2 3 4 5 |
foreach ($array as $value) { code; } |
The above syntax shows the following parameters,
- array- This is the array as represented by topics in the below example
- value-The array element value gets assigned to value.
Example
Here, we are printing the values of the given array topics:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <body> <?php $topics = array("Java", "Android", "Ruby"); foreach ($topics as $value) { echo "$value <br>"; } ?> </body> </html> |
Here’s the output,
No Comments