PHP Conditional Statements [if() switch()]
One thing you can do with PHP is add decision making capabilities to your scripts
The most common conditional statement is the if() statement, here is how it is used:
<?php
$number = 10;
if ($number == 10)
{
echo 'The number is ten!';
}
else
{
echo 'The number is not ten!';
}
?>
The result would be: The number is ten.
During this conditional statement we have come across another operator, the two equals signs and all these mean is explicitly equal to.
Here is a list of operators that you may need when using conditional statements:
== //equal to === //equal to and of the same type !== //not equal to and not of the same type <> //not equal to (same as !=) < //less than <= //less than or equal to > //greater than >= //greater than or equal to
So using our new found operators
we can now create another conditional statement:
<?php
$number = 10;
if ($number >= 11)
{
$result = 'The number is more than eleven or equal to eleven';
}
else
{
$result = 'The number is less than eleven';
}
?>
Now we can have instead of just two possibilities, we can add more using elseif():
<?php
$fruit = 'apple';
if ($fruit == 'apple')
{
$color = 'Red';
}
elseif ($fruit == 'Bannana')
{
$color = 'Yellow';
}
elseif ($fruit == 'Pear')
{
$color = 'Green';
}
else
{
$color = 'Unknown';
}
// Now display the data
echo "<p>The $fruit is $color</p>";
// In this example because the fruit was apple the color will output red so the string will read:
// The apple is red
// If you was to change the fruit to mango the the color would be unknown as there is no color set for mango:
// The mango is Unknown
?>
Switch statement coming very soon!
Nesting conditional statements
It is possible to nest conditional statements in order to handle multiple conditions and this is done so like this:
<?php
if ($shape == 'Square')
{
if ($color == 'Red')
{
if ($size == 'Large')
{
$item = 'The item is a large red square';
}
}
}
?>
You can use logical operators instead of nesting statements and this is done like this:
<?php
if ($shape == 'Square' && $color == 'Red' && $size == 'Large')
{
$item = 'The item is a large red square';
}
?>
Using logical operators is probably the better way to do things!
No related posts.

