Les conditions IF…ELSEIF…ELSE permettent d'exécuter certain code en fonction des conditions que l'on passe en paramètre.
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
?>