HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP if...else Statements

The if...else statements are fundamental control flow structures used to execute code based on certain conditions.

Syntax


if (condition) {
// code to be executed if condition is true;
} else {
// code to be executed if condition is false;
}

Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

Example


<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>
 
</body>
</html>

     

Output

Have a good day!

PHP - The if...elseif...else Statement


The if...elseif...else statement executes different codes for more than two conditions.

Syntax


if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}

Example


Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");
echo "

The hour (of the server) is " . $t; echo ", and will give the following message:

"; if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> </body> </html>

Output

The hour (of the server) is 10, and will give the following message: Have a good day!



Operator Name Result
and And True if both conditions are true
&& And True if both conditions are true
or Or True if either condition is true
|| Or True if either condition is true
xor Xor True if either condition is true, but not both
! Not True if condition is not true