4. Loops
A loop is used to repeat a set of instructions a defined number of times. This means you can perform the same task as many times as you need: once, none, x times; but not infinitely, because otherwise the HTML would never finish being generated. Each repetition is called an iteration.
There is nothing better than an example to prove its potential. If you run the following code...
<html>
<body>
<h1>How old are you?</h1>
<select>
<?php foreach (range(1, 10) as $num): ?>
<option value="<?php echo $num; ?>"><?php echo $num . ' years'; ?></option>
<?php endforeach; ?>
</select>
</body>
</html>
... it will generate this HTML for you.
<html>
<body>
<h1>How old are you?</h1>
<select>
<option value="1">1 years</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
<option value="6">6 years</option>
<option value="7">7 years</option>
<option value="8">8 years</option>
<option value="9">9 years</option>
<option value="10">10 years</option>
</select>
</body>
</html
Most likely the code looks indecipherable to your eyes and you are looking for the nearest window to jump out of. Stop! I am not interested yet in you understanding its meaning, but rather its potential. Despite its simplicity, with 3 lines of PHP we have generated 10 of HTML, and only because we stopped. Now imagine your boss asks you for a table with the years from 1890 to 2000. If you write a loop similar to the example, you will have it ready before the coffee machine finishes making you a cortado. Super useful! Can you imagine websites that use loops to simplify the work? I suggest you take a look at: shops, blogs, newspapers, social networks...
Within PHP there are 4 types of loops:
- foreach
- for
- while
- do-while
They are all different strategies when it comes to deciding the number of times you are going to iterate, but deep down they do the same thing. Let's see one by one how they work.
foreach
It is the simplest way to iterate over an array.
$animalesFantasticos = ['fénix', 'dragón', 'grifo', 'pegaso', 'cerbero'];
foreach ($animalesFantasticos as $animal) {
echo $animal . ' ';
}
// fénix dragón grifo pegaso cerbero
In case we need the key, there is another way to use it.
$animalesFantasticos = ['fénix', 'dragón', 'grifo', 'pegaso', 'cerbero'];
foreach ($animalesFantasticos as $posicion => $animal) {
echo "The animal $animal is at position $posicion \n";
}
// The animal fénix is at position 0
// The animal dragón is at position 1
// The animal grifo is at position 2
// The animal pegaso is at position 3
// The animal cerbero is at position 4
Regarding range(), it is a native PHP function that generates an array of elements. It accepts 2 or 3 parameters.
range($inicio, $fin, $pasos);
var_dump(range(10, 15));
/*
array(6) {
[0] =>
int(10)
[1] =>
int(11)
[2] =>
int(12)
[3] =>
int(13)
[4] =>
int(14)
[5] =>
int(15)
}
*/
var_dump(range(0, 100, 20));
/*
array(6) {
[0] =>
int(0)
[1] =>
int(20)
[2] =>
int(40)
[3] =>
int(60)
[4] =>
int(80)
[5] =>
int(100)
}
*/
To insert a loop inside HTML you have 2 ways. In the example it is written with foreach, but any loop or conditional is valid.
Classic syntax.
<html>
<body>
<?php foreach (range(1, 5) as $num) { ?>
<p><?php echo $num; ?></p>
<?php } ?>
</body>
</html>
Alternative syntax.
<html>
<body>
<?php foreach (range(1, 5) as $num): ?>
<p><?php echo $num; ?></p>
<?php endforeach; ?>
</body>
</html>
Both give the same result.
<html>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
</body>
</html>
Traversing multidimensional arrays
In order to read an array with more than one dimension, we will have to make nested loops. Or a loop inside another loop.
We start from an array, with 2 dimensions, that we saw in the previous lesson.
$zara = [
123 => [
'nombre' => 'Camisa a cuadros',
'precio' => 29.95,
'sexo' => 'Hombre'
],
234 => [
'nombre' => 'Falda manga',
'precio' => 19.95,
'sexo' => 'Mujer'
],
345 => [
'nombre' => 'Bolso minúsculo',
'precio' => 50,
'sexo' => 'Mujer'
]
];
If I wanted to show all the information of the products.
foreach ($zara as $producto) {
var_dump($producto);
}
/*
array(3) {
'nombre' =>
string(16) "Camisa a cuadros"
'precio' =>
double(29.95)
'sexo' =>
string(6) "Hombre"
}
array(3) {
'nombre' =>
string(11) "Falda manga"
'precio' =>
double(19.95)
'sexo' =>
string(5) "Mujer"
}
array(3) {
'nombre' =>
string(16) "Bolso minúsculo"
'precio' =>
int(50)
'sexo' =>
string(5) "Mujer"
}
*/
It has iterated 3 times, and each time it returned an array to me. What is contained inside the first array is other arrays. So I must traverse each one with another foreach.
foreach ($zara as $producto) {
foreach ($producto as $elemento) {
echo "$elemento \n";
}
}
// Camisa a cuadros
// 29.95
// Hombre
// Falda manga
// 19.95
// Mujer
// Bolso minúsculo
// 50
// Mujer
And now I do have it.
Nested loops can be made with any type of
loop. I recommend you always work withforeachwhenever you can, since it will be harder for you to end up with an infinite loop.
for
The most complex loop and the one most similar to other languages (C, Java, Javascript...).
for (variable inicio; condicional; incremento) {
...
}
for ($i = 0; $i < 10; $i++) {
echo "$i \n";
}
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
$i++is equivalent to$i += 1or$i = $i + 1. It basically increases the variable by 1. You also have its opposite:$i--.
while
It is the simplest and most dangerous loop. You must pay close attention so that it ends at some point.
while (condicional) {
...
}
$i = 1;
while ($i < 10) {
echo $i++;
}
// 123456789
do-while
It behaves the same as while, except that it commits to running at least once. Regardless of whether the conditional is met. The secret lies in the fact that first the instructions are executed and then the conditional is evaluated.
do {
...
} while (condicional)
$i = 1;
do {
echo $i++;
} while ($i < 10);
// 123456789
$i = 20;
do {
echo $i++;
} while ($i < 10);
// 20
Activity 1
- Tell me in each case whether it would enter the conditional.
1
if (True && True)
2
if (False && True)
3
if (1 == 1 && 2 == 1)
4
if ("test" == "test")
5
if (1 == 1 || 2 != 1)
6
if (True && 1 == 1)
7
if (False && 0 != 0)
8
if (True || 1 == 1)
9
if ("test" == "testing")
10
if (1 != 0 && 2 == 1)
11
if ("test" != "testing")
12
if ("test" == 1)
13
if (!(True && False))
14
if (!(1 == 1 && 0 != 1))
15
if (!(10 == 1 || 1000 == 1000))
16
if (!(1 != 10 || 3 == 4))
17
if (!("testing" == "testing" && "Zed" == "Cool Guy"))
18
if (1 == 1 && (!("testing" == 1 || 1 == 0)))
19
if ("chunky" == "bacon" && (!(3 == 4 || 3 == 3)))
20
if (3 == 3 && (!("testing" == "testing" || "PHP" == "Fun")))
Activity 2
- Ask for the year of birth.
- Calculate the age.
- If they are of legal age, tell them they can come in.
- If they are underage, throw them out.
- If they are over 65 years old, tell them they are too old to enter.
Pro:
- Get the year from the system instead of writing it by hand in a variable.
Pro2:
- Also ask for the day and month of birth to know whether they have had their birthday this year.
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.