Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP for and foreach statements

Generally, in PHP, for and foreach are used to traverse an array. Similar to while, for and foreach execute code while certain conditions are met.

for

The for statement has 3 expressions, the first one is the initial value of the iteration, or the value where the loop starts; the second one is the condition, the loop continues to execute until this one is false; and the 3rd one is how the iteration is done, if it goes value by value, if it jumps 2 values, or what it does.

Sintaxis / Sintax
for(expresion1; expresion2; expresion3){

}

There are times when we can come across code where some of these parameters are not specified. For example:

Example of for statement without some parameters specified
$contador = 0;
for (; $contador < 10; ) {
    // código a ejecutar en cada iteración
    $contador++;
}

Loop body

when we have our for loop, everything between { and } will be the body of the loop and will be the code that executes on each iteration, the same happens with while, do-while, and foreach.

Sintaxis / Sintax
//blastcoding.com
for (inicialización; condición; actualization) {
    // code that will run in every interaction
}

Infinite loops with for

In for statement we have 2 ways to create infinite loops, one is to specify the condition as true and the other is to specify nothing:

making an infinite loop using true as condition
for (true) {
    // Este código se ejecutará indefinidamente
}
making infinite loop without specifing initialization; condition; actualization
for (;;) {
    // Este código se ejecutará indefinidamente
}

foreach

With foreach, it's very easy to traverse an array or an object, and it only works with these two types of variables. If you use it on a common variable, it will give us an E_WARNING error.

Sintaxis / Sintax
foreach($array as $item){
    //bloque ejecutado mientra el array tenga miembros por recorrer
}

foreach($array as $key => $item){
    //bloque ejecutado mientra el array tenga miembros por recorrer
}

In the second case, $key will be the key where we are currently standing in the iteration or the current element of the array.

Altering the array

If I pass the value of an element by reference, for example &$value, my array will change forever.

Sintaxis / Sintax
foreach ($array as &$value) {
    // Modificar $value modificará el array original
}

Let's compare 2 examples so that this is understood.

Example 1
$nums = range(1, 5);

// Iterar sobre el array con foreach
foreach ($nums as $num) {
	$num= $num+1;
    echo $num . "\n";
}
print_r($nums);
2
3
4
5
6
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Example 2
$nums = range(1, 5);

// Iterar sobre el array con foreach
foreach ($nums as &$num) {
	$num= $num+1;
    echo $num . "\n";
}
print_r($nums);
2
3
4
5
6
Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)

PHP foreach examples

// Crear un array con los números del 1 al 5
$nums = range(1, 5);

// Iterar sobre el array con foreach
foreach ($nums as $num) {
    echo $num . "\n";
}

Let's look at an example using the second syntax:

$usuario = array(
    "nombre" => "Juan",
    "apellido" => "Pérez",
    "edad" => 30,
    "email" => "juan.perez@example.com",
    "telefono" => "123-456-7890"
);

// Iterar sobre el array con foreach
foreach ($usuario as $clave => $valor) {
    echo "$clave: $valor\n";
}
nombre: Juan
apellido: Pérez
edad: 30
email: juan.perez@example.com
telefono: 123-456-7890

Both foreach and while are commonly used to display data fetched from the database. Keep in mind that most of the time, the query we make to the database can be brought as if it were an array.

In the following link, you can see a brief summary about Control Structures in PHP.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category