PHP - Conditionals

Conditionals

Here are the most common conditional types:

  • Conditional statements allow your program to make choices
  • A computer can typically make two choices, true or false. You can "chain" them together to allow more choices
  • PHP v.5.3 adds support for jump labels which provides a limited goto functionality.
  • if
  • if .. else
  • elseif
  • switch

PHP - The if Statement

  • statement - executes some code if one condition is true

Example 1


<?php
$t = date("H");

if ($t < "20") {
echo "Have a good day!";
}
#Output "Have a good day!" if the current time (HOUR) is less than 20
?>

PHP - The if .. else Statement

  • The if .. else statement executes some code if a condition is true and another code if that condition is false.

Example 2


<?php
$t = date("H");

if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
#Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise
?>

PHP - The elseif Statement

  • The elseif statement executes different codes for more than two conditions.

Example 3


<?php
$t = date("H");

if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
#Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!"
?>

PHP - switch Statement

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

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

Example 4


<?php
$favcolor("red");

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
break;
}
#Output "Your favorite color is red!"
?>

Shorthand Conditionals

  • Here is how to assign a variable based on a condition.
    • if ($a > 10 ) $a=10;
    • Useful to make sure $a doesn't become greater than 10
  • There is a shorthand operation called the ternary operator which makes this faster to type and read:
    • (<condition>) ? <value of true> : <value of false>;
  • The above if conditional could be re-written using the ternary operator as..
<?php
$a = ($a > 10) ? 10 : $a;
?>

Post a Comment

Previous Post Next Post