PHP Tutorial: switch statement and for/foreach/while loops
Hello everyone, today we confront the topic switches to iterate over arrays and loops.
Switch
The switch statement is no more than one “alternative” to declare a series of if {} elseif {} elseif {} else {} with some small differences. Let’s look at this example:
$choice = 1;
switch ($choice) {
case 1:
echo "You have chosen 1!"
break;
case 2:
echo "You selected 2";
break;
case 3:
echo "You have chosen 3!"
break;
default:
echo "The selected number is neither 1, nor 2, nor 3";
break;
}
Guida PHP: istruzione switch e cicli for/foreach/while
Salve a tutti, oggi affronteremo l’argomento switch e cicli per iterare su array o su valori booleani.
Switch
L’istruzione switch altro non è che un metodo “alternativo” per dichiarare una serie di if {} elseif {} elseif{} else{} con delle piccole differenze. Analizziamo questo esempio:
$scelta = 1;
switch ($scelta) {
case 1:
echo "Hai selezionato 1!";
break;
case 2:
echo "Hai selezionato 2!";
break;
case 3:
echo "Hai selezionato 3!";
break;
default:
echo "Il numero selezionato non è ne 1, ne 2, ne 3!";
break;
}
Come si può facilmente intuire, l’istruzione switch è particolarmente utile quando ci si aspetta dei determinati valori da una variabile ed è buona norma usarlo per evitare lunghe istruzioni if di questo tipo:
$scelta = 1;
if ($scelta == 1)
echo "Hai selezionato 1!";
elseif ($scelta == 2)
echo "Hai selezionato 2!";
elseif ($scelta == 3)
echo "Hai selezionato 3!";
else
echo "La tua scelta non è ne 1, ne 2, ne 3!";
Se infatti provate ad eseguire queste due porzioni di codice, noterete che il risultato è identico. Si può dire quindi che l’istruzione switch è da utilizzare per rendere più “visibile” il codice e renderlo più snello e facilmente comprensibile.
Il ciclo for
Per chi viene da linguaggi come C o Java o Javascript, probabilmente sa già di cosa andremo a trattare. Il ciclo for è utile quando si vuole iterare (cioè scorrere gli elementi uno ad uno ed eseguire varie operazioni per ogni elemento) un array. Considerando il seguente esempio:
$array = array("primo","secondo","terzo");
for($i=0;$i=2;$i++) {
//...codice da eseguire
}
Si possono notare 3 parametri che compongono l’istruzione, che andremo ad elencare e descrivere:
- $i = 0; – Questo sta ad indicare che si assegna ad una variabile il valore di 0, e verrà utilizzato da contatore per scorrere la lista degli elementi (ricordate che gli array hanno una coppia di chiave->valore, e le chiavi si conteggiano da 0 e non da 1)
- $i <= 2; – Questa è una condizione, nel significato letterario sta ad indicare, esegui ciò che è alla destra di questo parametro fino a quando $i diventa uguale a 2 (più o meno come un if)
- $i++; – Questa è la condizione che viene ripetuta se il parametro precedente ritorna valore booleano TRUE
Ora che sappiamo quali sono i parametri da impostare possiamo modificare l’esempio sopra riportato nel seguente modo:
$array = array("primo","secondo","terzo");
for($i = 0;$i=2;$i++) {
echo $array[$i];
}
Questo esempio stamperà 3 stringhe, cioè “primo”, “secondo” e “terzo” in quanto abbiamo utilizzato $i per leggere i valori dell’array $array. Per provare provate a fare “echo $array[0]; echo $array[1];” e vedrete che il risultato sarà identico
A questo punto la domanda che sorge spontanea è: e se il mio array contiene anche un elemento “quarto” ?
Ovviamente seguendo l’esempio sopra riportato il quarto valore non verrà restituito, in quanto il secondo parametro del ciclo for e cioè: $i=2 ritornerà true quando arriverà all’elemento “terzo” (ricordatevi che si conta da 0). Ed è qui che ci viene in aiuto la funzione count().
$array = array("primo","secondo","terzo","quarto");
for ($i=0; $i<=count($array); $i++) {
echo $array[$i];
}
Come sicuramente avrete notato, non si usa più il segno di uguale (=) ma è stato cambiato in minore-o-uguale (<=). Questo perchè la funzione count, conta gli elementi di un array ma inizia il conteggio da 1 e il nostro array inizia il conteggio da 0 ! Per evitare questa incompatibilità si fa uso del simbolo minore-o-uguale così che anche se il conteggio arriva a 2 il nostro array è stato contato per tutti e 3 gli elementi.
Il ciclo foreach
Il ciclo foreach altro non è che un metodo più veloce e snello per ciclare un determinato array senza utilizzare il lungo ciclo for. Prendendo l’esempio precedente si potrà scrivere:
$array = array("primo","secondo","terzo","quarto");
foreach ($array as $key => $val) {
echo $val;
}
Questo esempio produrrà lo stesso risultato del ciclo for. Il primo argomento del ciclo è l’array da iterare, il secondo è un modo per assegnare alle variabile $key l’indice dell’elemento corrente e $val il valore a lui associato. Infatti scrivendo questa porzione di codice:
$array = array("primo","secondo","terzo","quarto");
foreach ($array as $key => $val) {
echo "Indice $key con valore $val";
}
Il risultato ottenuto sarà “Indice 0 con valore primo”, “Indice 1 con valore secondo” e così via. Da notare che il ciclo foreach, come l’istruzione if può essere scritta in diversi modi ottenendo lo stesso risultato.
Si può scrivere senza parentesi quando si vuole effettuare 1 sola operazione per il ciclo.
$array = array("primo","secondo","terzo","quarto");
foreach ($array as $key => $val)
echo "Indice $key con valore $val";
Si può scrivere con i due punti e un endforeach finale; metodo particolarmente utile quando si vuole inserire dei cicli direttamente nel codice HTML
$array = array("primo","secondo","terzo","quarto");
foreach ($array as $key => $val):
echo "Indice $key con valore $val";
endforeach;
Il ciclo while
Il ciclo while è un metodo alternativo per iterare su un espressione booleana e può essere rappresentato (come per i for o foreach) come una serie di if ripetute. Siccome a differenza di for o foreach while non ci dà nessun tipo di parametro da impostare per incrementare il contatore del nostro array, dovremo farlo noi.
$array = array("primo","secondo","terzo","quarto");
$i = 0;
while ($i <= count($array)) {
echo $array[$i];
$i++;
}
Il ciclo while che tradotto dall’inglese significa MENTRE, può essere tradotto in termini letterari “Fai questo MENTRE il valore è questo”. Ovviamente il risultato di questo ciclo sarà identico ad un ciclo for, foreach. Da notare che esiste una variante di while che può essere scritta in questo modo:
$array = array("primo","secondo","terzo","quarto");
$i = 0;
do {
echo $array[$i];
$i++;
} while ($i <= count($array));
Come sicuramente avrete capito il codice contenuto in do {} viene eseguito se il parametro fornito in while() ritorna true.
Siamo giunti al termine del nostro piccolo tutorial, nel prossimo post parleremo di come utilizzare le funzioni interne di PHP per gestire le stringhe, effettuare ricerche, sostituire pezzi di stringa eccetera.
Grazie per aver letto questo articolo, alla prossima!
As you can easily guess, the switch statement is especially useful when you expect certain values of a variable and is a good idea to avoid a long if statements like this:
$choice = 1;
if ($choice == 1)
echo "You have chosen 1!"
elseif ($choice == 2)
echo "You selected 2";
elseif ($choice == 3)
echo "You have chosen 3!"
else
echo "Your choice is neither one, nor two, nor 3";
In fact, if you try to perform these two pieces of code, you will notice that the result is identical. We can therefore say that the switch statement is used to make “visible” in the code and make it more streamlined and easily comprehensible.
The for loop
For those coming from languages like C or Java or Javascript, you probably already know what we’re going to deal with. The for loop is useful when you want to iterate (ie, iterate through the items one by one and perform various operations for each element) an array. Consider the following example:
$array = array ("first", "second","third");
for ($ i = 0; i = $ 2, $ i + +) {
//... Code to be executed
}
You may notice the three parameters that make up the loop, we’re going to list and describe:
- $ i = 0; – This means that you assign to a variable value of 0, and will be used as a counter to scroll the list of items (remember that arrays have a pair of key-> value, and the keys you count from 0, not 1)
- $ i <= 2 – This is a condition, in the literal meaning is to indicate, perform what is the right of this parameter, until $i is equal to 2 (like if)
- $i++ – This is the condition which is repeated if the previous parameter returns boolean TRUE
Now that we know what the parameters can be set to modify the example above as follows:
$array = array("first", "second","third");
for ($i = 0,$i = 2, $i++) {
echo $array [$i];
}
This example will print three strings, which means “first”, “second” and “third” because we used the $i to read the values of the array. For testing purpose try to do “echo $ array [0]; echo $ array [1],” and you will see that the result will be identical
Now the question that arises is: what if my array contains an element of “fourth”?
Of course, following the example above the fourth value will not be returned, as the second parameter of the loop, ie: $i=2 will return true when it comes to its “third” (remember that counts from 0). And this is where the count() function comes in help.
$array = array("first", "second","third","fourth");
for ($ i = 0; $i<= count($array) $i++) {
echo $array[$i];
}
As I’m sure you noticed, no longer uses the equal sign (=) but was changed to less-or-equal (<=). This is because the feature count(), count the elements of an array but it starts counting at 1 and our array starts counting from 0! To avoid this incompatibility makes use of the symbol-or-less equal so that even if the count reaches 2 our array was counted for all 3 elements.
The foreach
The foreach loop is nothing but a quicker and cleaner way to cycle a given array without using the for loop. Taking the above example you can write:
$array = array ("first","second","third","fourth");
foreach ($array as $key => $val) {
echo $val;
}
This example will produce the same result as the loop. The first argument of the loop is to iterate the array, the second is a way to assign the variable $key and the index of the current $val the value associated with him. In fact, writing this piece of code:
$array = array ("first","second","third","fourth");
foreach ($array as $key => $val) {
echo "$key index with value $val";
}
The result will be “index 0 with value first”, “Index value with a second” and so on. Note that the foreach loop, like the if statement can be written in different ways with the same results.
You can write without parentheses when you want to perform a single operation per cycle.
$array = array ("first","second","third","fourth");
foreach ($array as $key => $val)
echo "$key index with value $val";
You can write with a colon and a endforeach final method is particularly useful when you want to insert loops into HTML
$array = array ("first","second","third","fourth");
foreach ($array as $key => $val):
echo "$key index with value $val";
endforeach;
The while loop
The while loop is an alternative method to iterate over a Boolean expression and can be represented (as in the for or foreach) as a series of if repeated. Because unlike for foreach or while statement does not give us any kind of parameter to be set to increment the counter of our array, we do it ourselves.
$array = array ("first","second","third","fourth");
$i=0;
while ($i <= count($array)) {
echo $array[$i];
$i++;
}
The while loop which means translated from WHEREAS, can be translated into literary terms, “Do this while the value is this.” Obviously the result of this cycle will be identical to a for loop, foreach. Note that while there is a variant of which can be written as follows:
$array = array("first","second","third","fourth");
$i=0;
do {
echo $ array[$i];
$i++;
} While ($i <= count($array));
As I’m sure you understand the code in do {} is executed if the parameter provided in while () returns true.
It’s the end of our little tutorial in the next post will talk about how to use the internal functions of PHP to manage strings, search, replace pieces of string and so on.
Thank you for reading this article, see you to next post!