Learn PHP Programming

A backend server scripting language, and a powerful tool for making dynamic and interactive Web pages. Learn each topic with examples and output.

PHP Introduction
Control Structures
Php Forms
Php Advanced

PHP If Else

Very often when you write code, you want 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:

The if statement executes some code if one condition is true. Syntax :

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

For Example :

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

if ($t < "20") {
  echo "Have a good day!";
}
?>
Have a good day!

The if...else statement executes some code if a condition is true and another code if that condition is false.

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

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

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

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!":

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

Now that you have done if-else statements in Php, let's learn for loop in php


Share this page on :

=