In the course of building an application, we will definitely encounter an iterative process, whether it is for example displaying a table from a database, or a list of images for a photo gallery, and so on.
In this topic, we will try to understand the concept of looping in PHP programming. So that after you follow this article, you will become more familiar with loops and can apply them in real cases.
Prerequisites
- PHP programming basics
for
Loop
This loop will run the code block for the specified number of iterations.
Basic syntax:
for (initialization; condition; increment)
{
code to be executed;
}
Sample Case
For example we will display numbers ranging from 1–100, we can use the following syntax:
<?php
for ($i = 1; $i <= 100; $i++)
{
echo $i . "<br />";
}
?>
From the syntax above, for example, we only display even numbers:
<?php
for ($i = 1; $i <= 100; $i++)
{
if ($i % 2 == 0) echo $i . "<br />";
}
?>
Or for example only odd numbers:
<?php
for ($i = 1; $i <= 100; $i++)
{
if ($i % 2 != 0) echo $i . "<br />";
}
?>
while
Loop
The loop of code block performed as long as the specified condition is true
.
Basic syntax:
while (condition)
{
code to be executed;
}
Sample Case
The following example will display the numbers 1–10:
<?php
$x = 1;while ($x <= 10)
{
echo $x . "<br />";
$x++;
}
?>
do...while
Loop
This loop will always loop once, then iterate over as long as the specified condition is true
.
Basic syntax:
do
{
code to be executed;
}
while (condition);
Sample Case
The following example will display the numbers 1–10:
<?php
$x = 1;do
{
echo $x . "<br />";
$x++;
}
while ($x <= 10);
?>
foreach
Loop
Do a loop for each element in the array.
Basic syntax:
foreach (array as key => value)
{
code to be executed;
}
Sample Case
The following example will display the numbers 1–5:
<?php
$array = array(
"one",
"two",
"three",
"four",
"five",
);foreach ($array as $value)
{
echo $value . "<br />";
}
?>
If your array
data has a key
and value
pairs, you can do it like this:
<?php
$array = array(
0 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
);foreach ($array as $key => $value)
{
echo "The key:" . $key . " with value: " . $value . "<br />";
}
?>
Or if you are receiving data from a database, you can use the foreach
loop above by displaying the column name pair as key
and the column content as value
.
Conclusion
In this article, you have learned about loops in PHP along with examples of cases. Hopefully you have better understanding about the basics of looping that we often need to use in building an application.
Thank you for following this tutorial. See you in another tutorials.
If you appreciate and like the content, please support me by buying me a coffee. Click on the link below to support me: