PHP: If Else

The If-else fuction if PHP is very similar to that of C as shown in example below:

<?php
$sunlight = 1;
if ($sunlight == 1){
echo "sunlight present";
} else {
echo "sunlight not present";
}
?> 

Note, there is no “then” used as in most other programming languages, only curly braces ({}) are used to enclose if and else statements. The above example is pretty straight-forward and would output following result:

sunlight present

Thus, the condition operator on sunlight equal to 1 would result in the condition being true and hence, the output. Also, note that the condition is checked using condition operator (== and not =) as disccussed in the operator chapter.

Now, I would discuss another example with false condition :


<?php
$sunlight = 0;
if ($sunlight == 1){
echo "sunlight present";
} else {
echo "sunlight not present";
}
?> 

The aboe example is pretty straight-forward and would output following result:

sunlight not present

Because, $sunlight (remember variables in PHP start with $ sign) has been initialized to 0 and in the if operation, we are checking for condition $sunlight == 1 which is false, “sunlight not present’ is printed.

PHP: Using ElseIf

PHP Also provides IfElse to check for multiple conditions as follows:

Now, I would discuss another example with false condition :


<?php
$sunlight = 0;
if ($sunlight == 1){
echo "sunlight present";
} elseif ($sunlight == 0) {
echo "sunlight not present";
} else {
echo "sunlight not known";
}
?>

The aboe example is pretty straight-forward and would output “sunlight present” as follows:

sunlight present
For $sunlight= 0 , the output would have been “sunlight not present” and “sunlight not known” otherwise.

Comments on this entry are closed.

css.php