PHP - Simple Decisions with the if Statement

Introduction

The basic form of an if construct is as follows:

if (expression  ) {
   // Run this code
}
// More code here

If the expression inside the parentheses evaluates to true, the code between the braces is run.

If the expression evaluates to false, the code between the braces is skipped.

Demo

<?php

         $widgets = 23;/*from ww w  . ja v  a2s  .c  om*/
         if ( $widgets == 23 ) {
             echo "We have 23 widgets!";
         }
?>

Result

The first line of the script creates a variable, $widgets , and sets its value to 23.

Then an if statement uses the == operator to check if the value stored in $widgets does equal 23.

If it does, the expression evaluates to true and the script displays the message.

If $widgets doesn't hold the value 23, the code between the parentheses is skipped.

If you only have one line of code between the braces you can, in fact, omit the braces altogether:

Demo

<?php

     $widgets = 23;/*w ww. j a  v  a 2 s  .  com*/
     if ( $widgets == 23 )
         echo "We have exactly 23 widgets!";
?>

Result

Related Exercise