PHP - Statement if statement

Introduction

An if statement includes a conditional which evaluates a Boolean expression.

If the expression is true, it will execute everything inside its block of code.

A block of code is a group of statements enclosed by {}.

Demo

<?php 
     echo "Before the conditional."; 
     if (4 > 3) { 
        echo "Inside the conditional."; 
     } /*from   w w w.  j  a va2 s .c o m*/
     if (3 > 4) { 
        echo "This will not be printed."; 
     } 
     echo "After the conditional."; 
?>

Result

Here, we use two conditionals.

A conditional is defined by the keyword if followed by a Boolean expression in parentheses and by a block of code.

If the expression is true, it will execute the block, otherwise it will skip it.

You can use the keyword else to execute some block of code if the previous conditions were not satisfied.

Demo

<?php
    if (2 > 3) { 
        echo "Inside the conditional."; 
    } else { //from   www.  j av a 2 s .c  o  m
        echo "Inside the else."; 
    } 
?>

Result

Here, it will execute the code inside the else as the condition of the if was not satisfied.

You can add an elseif keyword followed by another condition and a block of code to continue asking PHP for more conditions.

You can add as many elseif as you need after an if.

If you add an else, it has to be the last one of the chain of conditions.

As soon as PHP finds a condition that resolves to true, it will stop evaluating the rest of conditions.

Demo

<?php

     if (4 > 5) { 
        echo "Not printed"; 
     } elseif (4 > 4) { 
        echo "Not printed"; 
     } elseif (4 == 4) { 
        echo "Printed."; 
     } elseif (4 > 2) { 
        echo "Not evaluated."; 
     } else { //from  ww  w .  j a  v  a  2 s.  c om
        echo "Not evaluated."; 
     } 
     if (4 == 4) { 
        echo "Printed"; 
     } 
?>

Result

Related Topics

Exercise