RCRAMER.COM
Clever website slogan
Home > Tech > PHP > Tests

PHP If...Else Statements

  • if statement - use this statement to execute some code only if the specified condition is true
  • if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false
  • if...elsif...else...statement - use this statement to select one of several blocks of code to be executed
  • switch statement - use this statement to select one of many blocks of code to be executed

The if Statement

Use the if statement to execute some code only if a specified condition is true.

if (condition) code to be executed if condition is true;
CodeOutput
<?php
$d=date("D");
if ($d=="Fri") echo "Happy Friday!";
?>
If it is Friday:
Happy Friday!

The if...else Statement

Use the if...else statement to execute different code depending on wether a condition is true or false.

if (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;
CodeOutput
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day"
?>
If it is Friday:
Have a nice weekend!

If it is NOT Friday:
Have a nice day!
<?php
$d=date("D");
if ($d=="Fri") {
  echo "Have a nice weekend!<br />";
  echo "See you on Monday!";
}
?>
If it is Friday:
Have a nice weekend!
See you on Monday!

Note: Use curly braces, { }, to enclose multiple lines.

The if...elseif...else Statement

if (condition)
  code to be executed if condition is true;
elseif
  code to be executed if condition is true;
else
  code to be executed if condition is false;
CodeOutput
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d="Sun")
  echo "Have a nice SUnday!";
else
  echo "Have a nice day"
?>
If it is Friday:
Have a nice weekend!

If it is Sunday:
Have a nice Sunday!

If it is NOT Friday or Sunday:
Have a nice day!

The switch Statement

Use the switch statement to select one of many blocks of code to be executed.

switch (n)
{ case mylabel1:
  code to be executed if n=myLabel1;
  break; case mylabel2:
  code to be executed if n=myLabel2;
  break; default:
  code to be executed if n != mylabel1 or myLabel2;
}

Each case statement in the sructure is compared to the expression, n, (usually a variable). If there is a match the code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is executed if no match is found.

CodeOutput
<?php
switch ($x)
{
case 1:
  echo "Number 1";
  break;
case 2:
  echo "Number 2";
  break;
case 3:
  echo "Number 3";
  break;
default:
  echo "No number between 1 and 3";
}
?>
If $x==1:
Number 1

If $x==2:
Number 2

If $x==3:
Number 3

If $x!=1 and $x!=2 and $x!=3:
No number between 1 and 3

See Comparison Operators for definitions of == and !=.