THE IF-ELSE STRUCTURE

php logo
It is a very important structure that we will use often because based on one or more conditions we decide the flow of program execution.

SUMMARY

if(condition(s)){
//inside the block we put the instructions in case the condition is verified
}else if (condition(s)){
//else if (otherwise if) is not mandatory. We can put as many ifs as we need.
} else {
//In all other cases….
}

SAMPLE CODE

<?php
//IF ELSE
//sintassi

/*if(condizione/i){
  all'interno del blocco mettiamo le istruzioni nel caso in cui la condizione è verificata
  }else if (condizione/i){ else if non è obbligatoria. Possiamo mettere tutti gli else if
    che ci servono.
  else{ In tutti gli altri casi....
  }
  E' una struttura molto importante che useremo spesso per chè in base a una o più condizioni
  decidiamo il flusso di esecuzione del programma.
}*/
$anni = 18;
if($anni < 12 ){
    echo 'Ha meno di 12 anni';
}else if ($anni >= 12 && $anni < 18){
    echo 'Ha tra i 12 e i 17 anni';
}else{
    echo 'Ha 18 anni o più'; 
}
/*--Spesso è probabile che dobbiamo mostrare un elemento HTML in base ad una condizione. Creiamo
un template HTML. Supponiamo che le voci di menù Home e Contatti siano visibili da chiunque*/
$isLogged = false;
?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <nav>
        <ul>
            <li><a href="">Home</a></li>
            <li><a href="">Contatti</a></li>
            <?php if ($isLogged === true) : ?><!--Possiamo usare i due punti al posto delle parentesi-->
                <li><a href="">Profilo</a></li>
            <?php else : ?>
                <li><a href="">Login</a></li>
            <?php endif; ?>
            
        </ul>
    </nav>
</body>
</html>

THE WHILE CYCLE.

SUMMARY

while(condition(s)){
//Let’s be careful not to create an infinite loop, that is, where the boolean condition is always true;
}
The while loop iterates a number of times over a block of instructions as long as the condition is true. It is important that there is an instruction to exit the loop otherwise infinite loops are created if the condition is always true crashing the system.

EXAMPLE CODE WHILE LOOP

<?php
//WHILE
$condizione = true;
$i = 0;
while($condizione === true){//Facciamo attenzione a non creare un loop infinito, dove cioè la condizione
                            //booleana è sempre true;Visualizziamo i risultati nel browser.
    if ($i <= 10){
        echo $i++, '<br>';
    }else{
        $condizione = false;
    }  
}
echo 'Dopo il cilo while...', '<br>';

$alunni = ['Marco' , 'Simona', 'Francesca'];
$numeroAlunni = count( $alunni );
$i = 0;
while ($i < $numeroAlunni){
    echo $alunni[$i++] . "<br>";
}

while ($alunno = array_pop ( $alunni )){
    echo $alunno, '<br>';
}
var_dump ($alunni); //Array vuoto abbiamo rimosso tutti gli elementi dell'array.
?>

CYCLE FOR

The for loop is similar to the while loop; they differ in that the for loop is more compact.

SUMMARY

for (expr1;expr2;expr3){
In the while loop the first thing we did was initialize a variable to zero. In the for we do this internally with expr1 which will be executed only once, that is, when PHP meets the for. expr2 is the condition, In expr3 we increase the variable. Put
such a variable at the head of the for is like removing it and putting it
as the last instruction within the loop.
}

EXAMPLE CODE OF THE FOR LOOP

<?php
//CICLO FOR
$alunni = ['Marco' , 'Simona', 'Francesca'];
$numeroAlunni = count( $alunni );
$i = 0;
while ($i < $numeroAlunni){
    echo $alunni[$i++] . "<br>";
}/*--Il ciclo for è un pò quello che abbiamo fatto con il ciclo while*/

/*--SINTASSI DEL FOR. Nel while la prima cosa che facevamo era inizializzare
*una variabile a zero. Nel for lo facciamo internamente. expr1 verrà eseguita
solo una volta, cioè quando PHP incontra il for. exr2 è la condizione,
$i < $numeroAlunni. In expr3 incrementiamo la variabile contatore. Mettere
$i++ all'interno del for è come se la togliessimo e la mettessimo
come ultima istruzione all'interno del for. La condizione viene verificata
ogni volta che raggiungiamo l'ultima istruzione all'interno del for. Per quanto
riguarda la prima e la terza espressione possiamo anche non indicarle, l'importante
è inizializzare la variabile fuori dal for, e fare il post incremento come
ultima istruzione. Sicuramente il ciclo for risulta più compatto rispetto al
ciclo while./

//SINTASSI
for (expr1; expr2; expr3){

}
*/
for ($i = 0; $i < $numeroAlunni; $i++){
     
    echo $alunni[$i] . '<br>';
}
$i = 0;
for (; $i < $numeroAlunni; ){
     
    echo $alunni[$i] . '<br>';
    $i++;
}


/*--Se vogliamo partire dall'ultimo elemento scriveremo:*/

for ($i = $numeroAlunni -1; $i >= 0; $i--){

    echo $alunni[$i] . '<br>';
}
?>

THE FOREACH LOOP

Thanks to the while loop and the for loop we were able to display the elements of an ordered array. Now we ask how do we display the elements of an associative array? The answer is given to us by the foreach loop.

SAMPLE CODE

<?php
//CICLO FOREACH
$user = [
    'nome' => 'Matteo',
    'professione' => 'Medico',
    'anni' => 32
];
/*--Stiamo praticamente dicendo: Per ogni valore dell'array associativo $user esegui
le istruzioni definite nel corpo del foreach. Visualizzare gli esempi nel browser.*/

foreach ( $user as $valore ){
      echo $valore , '<br>';
}
foreach ( $user as $chiave => $valore ){
    echo " $chiave : $valore " , '<br>';
}
$user = [
    'nome' => 'Matteo',
    'professione' => ['Medico','Ricercatore'],
    'anni' => 32
];
foreach ( $user as $chiave => $valore ){
    echo "$chiave: ";
    if ( !is_array($valore) ){

        echo $valore  , '<br>';

    }else{

        echo implode(", " , $valore),'<br>';
    }
   
}
?>

THE BREAK AND CONTINUOUS INSTRUCTIONS

With the instructions break e continue we can respectively exit a loop prematurely or skip the current iteration. To show the break instruction we will use the dice game, while to continue the code will be simpler.

SAMPLE CODE

<?php
//BREAK AND CONTINUE
function lanciaDadi(){
    $dado1 = [1,2,3,4,5,6];
    $dado2 = [1,2,3,4,5,6];
    return $dado1[rand(0,5)] + $dado2[rand(0,5)];
}
$lanci = 20;

for ($i = 1; $i <= 20; $i++){
    $risultato = lanciaDadi();
    echo "lancio numero: $i ", "risultato: $risultato ".'<br>';
    if ($risultato === 7){
        echo "Hai vinto!!!";
        break; //Interrompe il for. Con break terminiamo il ciclo.
    }
}
for ($i = 1; $i <= 10; $i++)
{
    if ($i === 5){
        continue; //salta l'iterazione corrente (5)
    }
    echo "$i <br>";
}
?>

THE SWITCH STRUCTURE

This structure is similar to the if-else conditional structure only that it is better from the point of view of readability when we have many else if in cascade. Let’s immediately see a code example to clarify the switch.

SAMPLE CODE

<?php
//SWITCH
$errorCode = 404;
$errorCode = "404";//Conversione automatica ad intero
switch ($errorCode){
   case 401: echo "Non autenticazione";
   break;
   case 403: echo "Non autorizzazione";
   break;
   case 404: echo "Not found";
   break;
   case 500: echo "Errore server";
   break;
}

$errorCode = 400;//In questo caso alcuni blocchi dello switch sono vuoti, PHP prosegue su un'altra riga
//non essendoci un break.
switch ($errorCode){
   case 401: 
   case 403: 
   case 404: echo "Errore richiesta";
   break;
   case 500: echo "Errore server";
   break;
   default: echo "Codice di errore non riconosciuto"; //default è un pò come else nella struttura if-else.
   //default deve essere l'ultima istruzione all'interno dello switch. Se cancelliamo default
   //anche se non c'è alcuna corrispondenza all'interno dello switch non c'è errore.
}
?>

MATCH (PHP 8)

Let’s clarify right away what it does Match instead of Switch with some code.

SAMPLE CODE

<?php
//MATCH (PHP 8)
$errorCode = "502";
/*switch ($errorCode){
   case 401: 
   case 403: 
   case 404: echo "Errore richiesta";
   break;
   case 500: echo "Errore server";
   break;
}*/
//match è un'espressione quindi ritorna un valore. Esegue un confronto stretto, quindi non si può
//usare una stringa "404" andrebbe in errore controllando il tipo se non esiste un default. In match dobbiamo per forza
//avere una corrispondenza, oppure usiamo default, nello switch non veniva segnalato un errore se non vi era
//corrispondenza nei case.
$msg = match( $errorCode ){
     401,403,404 => 'Errore richiesta',
     500, 502 => 'Errore interno del server',
     default => 'Codice di errore non riconosciuto'
};
echo $msg;
?>

THE KEYWORDS INCLUDE AND REQUIRE

We can write thousands of lines of code in a script, but this is not optimal from an organizational and structural point of viewas well as for the management of the code itself. In PHP we can split a script into multiple files to have small fragments and import them with REQUIRE and INCLUDES. If the imported code is critical to the script we use REQUIRE, otherwise if not strictly necessary INCLUDES.

SAMPLE CODE

<?php
//REQUIRE E INCLUDE
/*--Possiamo scrivere migliaia di righe di codice in uno script,
ma ciò non è ottimale da un punto di vista organizzativo e strutturale
nonchè la gestione del codice stesso. In PHP possiamo suddividere uno script in
più files per avere script di piccole dimensioni e importarle con REQUIRE E INCLUDE
Se il codice importato è fondamentale per lo script usiamo REQUIRE, altrimenti se non
è strettamente necessario INCLUDE.*/


/*--Con include se lo script non viene trovato abbiamo un warning, ma l'esecuzione continua
con require l'esecuzione si arresta e abbiamo un fatal error*/
require 'funzioni.php';
/*--E' come se facessimo un copia e incolla all'interno dello script.*/
fn1();
fn2();
require 'a.php';
require 'b.php';
/*--E' come se facessimo un copia e incolla all'interno dello script.*/
$nomeCorso = "Corso PHP";
$nomeCorso = "Corso Javascript";//sovrascrive la variabile.

echo $nomeCorso;
?>

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB