PHP for Beginners: Conditionals
Conditional statements are used to preform different actions based on different conditions. In PHP, there are four conditional statements: if – execute code only if a specefied condition is true, if…else – execute code if a condition is true and another code if the condition is false, if…elseif…else – select one of several blocks of code to be executed, and switch – select one of many blocks of code to be executed.
Examples:
The if statement has the following syntax:
<?php
$d=date ("D");
if ($d=="Fri")
echo "Have a nice weekend!";
?>
The if…else statement has the following syntax:
<?php
$d=date ("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
The if…elseif…else statement has the following syntax:
<?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!";
?>
The following example shows the basic use of the switch statement:
<?php
switch ($x)
{
case 1: echo "$x is 1";
break;
case 2: echo "$x is 2";
break;
case 3: echo "$x is 3";
break;
default:
echo "$x is not 1, 2, or 3";
}
?>



