If abbreviato nella costruzione if-else
Supponiamo, ad esempio, di voler sapere se la variabile
$test è uguale al valore true.
In questo caso la costruzione if può
essere scritta così:
<?php
$test = true;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
In programmazione, tali controlli sono richiesti
molto spesso, quindi per essi esiste una forma
abbreviata più elegante: invece di if ($test
== true) si può scrivere semplicemente if
($test).
Riscriviamo il nostro codice in forma abbreviata:
<?php
$test = true;
if ($test) { // equivalente a if ($test == true)
echo '+++';
} else {
echo '---';
}
?>
Supponiamo ora di voler verificare che la variabile
$test non sia uguale a true:
<?php
$test = true;
if ($test != true) {
echo '+++';
} else {
echo '---';
}
?>
In questo caso la sintassi abbreviata sarà così:
<?php
$test = true;
if (!$test) { // usiamo la negazione logica NOT
echo '+++';
} else {
echo '---';
}
?>
Esiste una abbreviazione analoga anche per la verifica
di false. Supponiamo di avere questo codice:
<?php
$test = true;
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
La condizione $test == false in realtà
equivale a $test != true:
<?php
$test = true;
if ($test != true) { // equivalente a if ($test == false)
echo '+++';
} else {
echo '---';
}
?>
Bene, e una condizione del genere abbiamo già imparato ad abbreviarla nell'esempio precedente. Abbreviamo:
<?php
$test = true;
if (!$test) {
echo '+++';
} else {
echo '---';
}
?>
Riscrivi il seguente codice utilizzando il confronto abbreviato:
<?php
$test = true;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
Riscrivi il seguente codice utilizzando il confronto abbreviato:
<?php
$test = true;
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
Riscrivi il seguente codice utilizzando il confronto abbreviato:
<?php
$test = true;
if ($test != true) {
echo '+++';
} else {
echo '---';
}
?>
Riscrivi il seguente codice utilizzando il confronto abbreviato:
<?php
$test = true;
if ($test != false) {
echo '+++';
} else {
echo '---';
}
?>