Guida PHP: L’istruzione if
Salve, oggi -come accennato nel post precedente- parleremo dell’istruzione if.
if, tradotto dall’inglese significa “se” e ci servirà per controllare in un determinato punto di una determinata funzione, se qualcosa va come abbiamo previsto..ma vediamo subito un esempio pratico per capire meglio:
/**
Questo valore sarà un integer, per maggiori informazioni sui tipi di dato visitate il post http://blog.wardrome.com/2011/05/browser-game-school-getting-started-with-php/
*/
$variabile = 1;
if (is_integer($variabile)) {
echo '$variabile è un intero!';
} elseif (is_string($variabile)) {
echo '$variabile è una stringa!';
} else {
echo '$variabile non è ne un numero, nè una stringa';
}
PHP Tutorial: The if statement
Hi, today -as mentioned in previous post- we will talk about the if statement.
The if statement is useful when we need to check at a given point in a specific function, if things go as we planned .. but let’s see a practical example:
/**
This value is an integer, for more information about data types, visit the post http://blog.wardrome.com/2011/05/browser-game-school-getting-started-with-php/
*/
$var = 1;
if (is_integer ($ variable)) {
echo '$variable is an integer!';
} Elseif (is_string ($ variable)) {
echo '$variable is a string!';
Else {}
echo '$variable is neither a number nor a string';
}
Questo esempio ovviamente produrrà sempre il risultato ‘$variabile è un intero’ visto che la variabile $viariabile è, per l’appunto, dichiara come intero. Per quanto riguarda l’elseif -sempre traducendo dall’inglese- è l’equivalente della espressione logico “Se non è un intero e se is_string (cioè se è una stringa) scrivi $variabile è una stringa”. Il parametro else, invece, si può pensarlo come “Se non è nè intero, nè stringa allora scrivi ‘$variabile non è ne un numero, nè una stringa’.
Per esercitarsi, provate a cambiare il valore di $numero e impostatelo come stringa ad esempio:
$variabile = "Sono una stringa";
// [...resto del codice...]
Il risultato fornito sarà sempre ‘$variabile è una stringa!’.
Gli operatori di confronto
Gli operatori di confronto servono, appunto, per confrontare 2 tipi di dati all’interno di un’istruzione if e forniranno un risultato booleano (true o false).
== Sta ad indicare UGUALE A [valore]
!= Sta ad indicare DIVERSO DA [valore]
=== Sta ad indicare IDENTICO A [valore] (cioè uguali e dello stesso tipo, ad esempio due interi)
> Sta ad indicare MAGGIORE DI [valore]
>= Sta ad indicare MAGGIORE O UGUALE DI [valore]
< Sta ad indicare MINORE DI [valore]
<= Sta ad indicare MINORE O UGUALE A [valore]
Vediamo alcuni esempi che analizzeranno ogni singolo operatore:
$valore = 5;
if ($valore == 5) { echo '$valore equivale a 0!'; }
if ($valore != 0) { echo '$valore è diverso da 1!'; }
if ($valore === 5) { echo '$valore è identico a 0!'; }
if ($valore > 1) { echo '$valore è maggiore di 1!'; }
if ($valore >= 3) { echo '$valore è maggiore o uguale a 3!'; // in questo caso sarà maggiore di 3 }
if ($valore < 6) { echo '$valore è minore di 6!'; }
if ($valore <= 6) { echo '$valore è minore o uguale a 6!'; // in questo caso sarà minore di 6 }
Importante: vista la debole tipizzazione del linguaggio PHP, bisogna fare molta attenzione quando si dichiara una viariabile racchiusa tra apici ‘ ‘ o ” “. Infatti considerando il seguente esempio:
$valore = 5;
$valore2 = "5";
if ($valore2 == $valore) {
echo 'Le 2 variabili sono uguali";
} else {
echo 'Le 2 variabili non sono uguali';
}
Anche se $valore nel momento della sua dichiarazione è un intero, mentre $valore2 è una stringa (perchè racchiusa tra apici ” “) il risultato ottenuto da questa istruzione sarà “Le 2 variabili sono uguali”, questo perchè PHP converte automaticamente $valore in stringa per effettuare il controllo dei 2 valori.
Consideriamo invece un altro esempio:
$valore = 5;
$valore2 = "5 persone al mio tavolo";
if ($valore == $valore2) {
echo "Le 2 variabili sono uguali";
} else {
echo "Le 2 variabili non sono uguali";
}
Probabilmente starete pensando che il risultato della precedente istruzione sarà “Le 2 variabili NON sono uguali”…ma invece non è così. Questo è dovuto al fatto che PHP converte automaticamente la variabile $valore2 in intero per confrontarla con $valore, eliminando tutto ciò che non è un intero. Quindi il valore di $valore2 nell’istruzione if sarà 5, e non “5 persone al mio tavolo”.
Ma invece se consideriamo il seguente esempio:
$valore = 5;
$valore2 = "5 persone al mio tavolo";
if ($valore === $valore2) {
echo "Le 2 variabili sono identiche";
} else {
echo "Le 2 variabili NON sono identiche";
}
L’esempio sopra riportato darà come risultato “Le 2 variabili NON sono identiche” e questo perchè si è usato l’operatore di controllo (===) che, come spiegato sopra, controllerà se le 2 variabili sono IDENTICHE (sia di valore che di tipo).
Gli operatori logici
Gli operatori logici ci permettono di concatenare due o più espressioni booleane, per permetterci di controllare uno o più dati all’interno della stessa riga (senza ripetere if {} elseif {} elseif {} ). Gli operatori logici sono quattro, e sono:
OR o || - Controlla se almeno uno dei due operatori è true; si può utilizzare OR o || (doppio pipe)
AND o && - Controlla se entrambi gli operatori sono true; si può utilizzare AND o && (la e commerciale)
Xor - Controlla se uno solo dei due operatori è true mentre l'altro deve essere false.
! - Il punto esclamativo equivale ad una negazione, è vero quando il valore è false, false viceversa.
Se la lista sopra riportata può risultare confusionaria, vediamo di considerare questo esempio:
$variabile = 14; // E' un integer
if (is_integer($variabile) && $variabile > 12 && $variabile !== 0) {
echo "E' un intero, è maggiore di 12, è diverso da 0";
}
Nel precedente esempio, controlliamo se $variabile è un intero, se è maggiore di 12, e se è diverso da 0. Da notare che per visualizzare il messaggio (echo) tutte le istruzioni fornite devono essere VERE.
Per esercitarvi, provate a scrivere questo codice:
$variabile = 11;
if (is_integer($variabile) && $variabile > 12 && $variabile !== 0) {
echo "E' un intero, è maggiore di 12 ed è diverso da 0";
} else {
echo "Istruzione fallita";
}
Se provate ad eseguire il precedente esempio potrete notare che il messaggio restituito sarà “Istruzione fallita” in quanto la condizione “$variabile > 12” non sarà true (in quanto $variabile è 11 quindi inferiore a 12).
Vediamo ora di analizzare il caso OR (o ||) prendendo come spunto l’esempio precedente.
$variabile = 0;
if (is_integer($variabile) || $variabile > 12 || !is_string($variabile) {
echo "Soddisfa almeno una condizione!";
} else {
echo "Non soddisfa nemmeno una condizione!";
}
Eseguendo questo codice le condizioni $variabile > 12 e !is_string($variabile) ritorneranno false, ma la condizione is_integer($variabile) ritornerà true quindi il messaggio visualizzato sarà “Soddisfa almeno una condizione!”. Per vedere il caso opposto, ci basterà cambiare il valore di $variabile nel seguente modo:
$variabile = "Stringa";
//[...resto del codice...]
Così facendo, tutte le condizioni ritorneranno false in quanto $variabile non sarà ne un intero, ne maggiore di 12 e non è diverso da una stringa (!is_string).
Sugli operatori logici c’è un discorso troppo ampio e complesso per poterlo scrivere qui, il mio consiglio è quello di esercitarsi per testare i vari risultati ottenuti.
Nelle prossime lezioni parleremo dell’istruzione switch e i cicli per eseguire operazioni ripetute. Alla prossima!
This example of course, will always produce the result ‘$variable is an integer’ as the variable $viariabile is, precisely, declared as integer. The elseif instruction can be translated to “If it is not an integer, and if is_string (ie if a string) print $variable is a string.” The parameter else instead, you can think of it as “If it is neither complete nor string then write ‘$variable is neither a number nor a string’.
To practice, try to change the value of $ number and set it as a string for example:
$variable = "I am a string";
/ / [... Rest of code ...]
The result will always be supplied ‘$variable is a string!’.
Comparison operators
Comparison operators are, in fact, to compare two types of data within an if statement and will provide a Boolean result (true or false).
== What is meant is equal to [value]
! = Is used to indicate other than [value]
=== Is used to indicate SAME [value] (that is equal and the same type, such as two integers)
> What is meant is greater than [value]
> = Is used to indicate greater or equal to [value]
<Is used to indicate LESS THAN [value]
<= It indicates Less or equal to [value]
Here are some examples that will describe each operator:
$value = 5;
if ($ value == 5) { echo '$value equals to 5!'; }
if ($ value! = 0) { echo '$value is not 0!';}
if ($ value === 5) { echo '$value is the same as 5!'; }
if ($ value > 1) { echo '$value is greater than 1!'; }
if ($ value> = 3) { echo '$value is greater than or equal to 3!'; } / / in this case will be greater than 3}
if ($ value < 6) { echo '$value is less than 6!'; }
if ($ value <= 6) { echo '$ value is less than or equal to 6!'; } / / in this case will be less than 6}
Important: Due to the weak identification of the PHP language, we must be very careful when you declare a viariabile enclosed in quotes '' or "." In fact, considering the following example:
$value = 5;
$value2 = "5";
if ($value == $value2) {
echo 'The two variables are equal ";
else {
echo 'The two variables are not equal';
}
Even if $value at the time of his statement is an integer, and $value2 is a string (enclosed in quotes because ") the result obtained by this instruction will be" The two variables are equal ", this is because PHP automatically converts the value in $string to maintain control of the 2 values.
Consider instead another example:
$value = 5;
$value2 = "5 people at my table";
if ($value == $value2) {
echo "The two variables are equal";
else {
echo "The two variables are not equal";
}
You're probably thinking that the result of the previous statement will be "The two variables are not equal" ... but is not so. This is because PHP automatically converts the variable $value2 in whole to compare it to $value, removing everything that is not an integer. So the value of $value2 in the if statement will be 5, not "5 people at my table."
But instead if we consider the following example:
$value = 5;
$value2 = "5 people at my table";
if ($value === $value2) {
echo "The two variables are identical;
else {
echo "The two variables are not identical;
}
The above example will result in "The 2 variables are not identical" and that's because you used the control operator (===) which, as explained above, check whether the two variables are identical (both in value type).
Logical operators
Logical operators allow us to concatenate two or more Boolean expressions, so that we can control one or more data within the same line (without repeating if {} {} elseif {} elseif {}). Logical operators are four, and they are:
OR or | | - Check if at least one of the two operators is true, you can use OR or || (double pipe)
AND or && - Check if both operators are true, you can use AND or && (the ampersand)
Xor - Check if only one of two operators is true while the other must be false.
! - The exclamation point is tantamount to a denial, it is true when the value is false or vice versa.
If the above list can be confusing, let's consider this example:
$variable = 14; / / It's an integer
if (is_integer($variable) && $variable > 12 && $variable !== 0) {
echo "It 's an integer, is greater than 12 and is not 0";
}
In the previous example, we check if $variable is an integer, if greater than 12, and if it is different from 0. Note that to view the message (echo) all instructions provided must be true.
For practice, try to write this code:
$variable = 11;
if (is_integer($variable) && $variable > 12 && $variable !== 0) {
echo "It 's an integer, is greater than 12 and is different from 0;
else {
echo "Failed";
}
If you try to run the above example you will notice that the message returned is "Failed" because the condition "$variable> 12" will not be true (because $variable is less then 11 to 12).
Let us now analyze the case OR (or ||), taking as inspiration the example above.
$variable = 0;
if (is_integer($variable) || $variable > 12 || !is_string ($variable) {
echo "It meets at least one condition!"
else {
echo "Do not even satisfy a condition!"
}
Running this code, the variable conditions
$variable > 12 and
!is_string($variable) will return false, but the condition is_integer($variable) will return true then the message will be displayed "It meets at least one condition. " To see the opposite case, we simply change the value of $variable as follows:
$variable = "string";
//[... Rest of code ...]
In so doing, all the conditions will return false because $ variable will not be an integer, greater than 12 and it is no different from a string (!is_string).
On the logical operators is a speech too large and complex to be able to write here, my advice is to practice to test the different results.
In the next lesson we will talk about the switch and to perform repeated cycles. See you next time!