ptg16476052
The PHP Language 661
24
string and does not terminate it. The other option is to use single quotes and employ the
string concatenation operator to include the value of $class in the string.
Conditional Statements
Conditional statements and loops are the bones of any programming language. PHP is
no different. The basic conditional statement in PHP is the if statement. Here’s how it
works:
if ($var == 0) {
echo "Variable set to 0.";
}
The code inside the brackets will be executed if the expression in the if statement is true.
In this case, if $var is set to anything other than 0, the code inside the brackets will not
be executed. PHP also supports else blocks, which are executed if the expression in the
if statement is false. They look like this:
if ($var == 0) {
echo "Variable set to 0.";
} else {
echo "Variable set to something other than 0.";
}
When you add an else block to a conditional statement, it means that the statement will
always do something. If the expression is true, it will run the code in the if portion of the
statement. If the expression is not true, it will run the code in the else portion. Finally,
there’s el seif:
if ($var == 0) {
echo "Variable set to 0.";
} elseif ($var == 1) {
echo "Variable set to 1.";
} elseif ($var == 2) {
echo "Variable set to 2.";
} else {
echo "Variable set to something other than 0, 1, or 2.";
}
As you can see, elseif allows you to add more conditions to an if statement. In this
case, I added two elseif conditions. There’s no limit on elseif conditions—you can use
as many as you need. Ultimately, elseif and else are both conveniences that enable you
to write less code to handle conditional tasks.