Google News
logo
PHP if...else Statements

PHP Conditional Statements

PHP if else statement to perform different actions for different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements :

  • if statement 
  • if...else statement
  • if...elseif....else statement
  • switch statement

PHP if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to true.
Syntax
if(condition){
    // Code to be executed
}
The following example of if statement :
<!DOCTYPE html>
<html>
<head>
	<title>PHP if statement</title>
</head>

<body>

  <?php
    $time = date("H");
    if ($time < "18") {
        echo "Have a good day!";
    }
  ?>

</body>
</html>
Output :
PHP if...else Statement

PHP if-else statement is executed whether condition is true or false.

Syntax
if(condition){  
   //code to be executed if true  
}else{  
  //code to be executed if false  
The following example of if...else statement :
<!DOCTYPE html>
<html>
<head>
	<title>PHP if...else statement</title>
</head>

<body>

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

if ($time < "18") {
    echo "Hi, have a good day!";
} else {
    echo "Hi, have a good night!";
}
?>

</body>
</html>
Output :
PHP if...elseif....else Statement

The if-else-if-else statement lets you chain together multiple if-else statements, thus allowing the programmer to define actions for more than just two possible outcomes.

Syntax
if (condition) {
    //code to be executed if true;
} elseif (condition) {
    //code to be executed if true;
} else {
    //code to be executed if false;
}
The following example of if...elseif...else statement :
<!DOCTYPE html>
<html>
<head>
	<title>PHP if...elseif....else statement</title>
</head>

<body>

<?php
	$time = date("H");
	if ($time < "11") {
		echo "Have a good morning!";
	} elseif ($time < "18") {
		echo "Have a good day!";
	} else {
		echo "Have a good night!";
	}
?>

</body>
</html>
Output :