PHP if...else Statements

PHP - The if...else Statement


if...else statements allow you to execute a block of code based on whether a condition evaluates to true or false. The if part handles the condition you want to check, and the else part provides an alternative set of code to execute when the if condition is not met.


Syntax of if...else


if (condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}
Example
<!DOCTYPE html>
<html>
<body>
<?php
$age = 16;

if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
?>
</body>
</html>

Try it yourself

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


if...elseif...else statements in PHP allow you to evaluate multiple conditions in a sequential manner. When a condition is met (i.e., evaluates to true), the corresponding block of code is executed, and the remaining elseif or else blocks are skipped. This is useful for implementing complex conditional logic.


Syntax of if...elseif...else


if (condition1) {
    // Code to be executed if condition1 is true
} elseif (condition2) {
    // Code to be executed if condition2 is true
} elseif (condition3) {
    // Code to be executed if condition3 is true
} else {
    // Code to be executed if all conditions are false
}
Example
<!DOCTYPE html>
<html>
<body>
<?php
$time = 15;

if ($time < 12) {
echo "Good morning!";
} elseif ($time < 18) {
echo "Good afternoon!";
} elseif ($time < 22) {
echo "Good evening!";
} else {
echo "Good night!";
}
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.