L'instruction IF…ELSEIF…ELSE est une instruction conditionnelle de base en PHP. Avec cette instruction, vous pouvez vérifier plusieurs cas différents et exécuter du code en fonction de celui qui correspond. Pour créer une instruction IF…ELSEIF…ELSE, vous devez d'abord fournir la comparaison à vérifier ainsi que les différents cas que vous souhaitez vérifier.
Après cela, vous devez fournir le code à exécuter lorsque la condition est remplie. Par exemple, supposons que vous souhaitiez faire une vérification d'un jour de la semaine et faire quelque chose de différent selon le jour :
if ($day_of_week == "Monday") {
// Code to be executed on Monday
} elseif ($day_of_week == "Tuesday") {
// Code to be executed on Tuesday
} elseif ($day_of_week == "Wednesday") {
// Code to be executed on Wednesday
} else {
// Code to be executed if none of the other cases are true
}
Vous pouvez également utiliser la partie ELSE de l'instruction pour fournir une option par défaut qui est exécutée si aucun des autres cas n'est vrai. Cela garantit que votre code gère correctement les entrées inattendues.
PHP : Condition IF
<?php
$x = 42;
if ( 42 == $x ) {
echo '$x is the answer to the Ultimate Question of Life, The Universe, and Everything';
}
// Display :
// $x is the answer to the Ultimate Question of Life, The Universe, and Everything
?>
PHP : Condition IF…ELSE
<?php
$x = 23;
if ( 42 == $x ) {
echo '$x is the answer to the Ultimate Question of Life, The Universe, and Everything';
} else {
echo '$x is different to 42.';
}
// Display :
// $x is different to 42.
?>
PHP : Condition IF…ELSEIF...ELSE
<?php
$x = 42;
if ( $x < 42 ) {
echo '$x is less than 42';
} elseif ( $x == 42 ) {
echo '$x is the answer to the Ultimate Question of Life, The Universe, and Everything';
} else {
echo 'x is greater than 42';
}
// Display :
// $x is the answer to the Ultimate Question of Life, The Universe, and Everything
?>
PHP : Condition IF... ENDIF
Il est possible en PHP de créer des conditions IF ... ELSEIF ... ELSE sans accolades en utilisant le symbole deux points (":") et le mots clé ENDIF comme ci-dessous :
<?php
$x = 42;
if ( 42 == $x ) : ?>
$x is the answer to the Ultimate Question of Life, The Universe, and Everything
<?php endif;
// Display :
// $x is the answer to the Ultimate Question of Life, The Universe, and Everything
?>
<?php
$x = 42;
if ( $x < 42 ) : ?>
$x is less than 42
<?php elseif ( $x == 42 ) : ?>
$x is the answer to the Ultimate Question of Life, The Universe, and Everything
<?php else : ?>
x is greater than 42
<?php endif;
// Display :
// $x is the answer to the Ultimate Question of Life, The Universe, and Everything
?>