Operators, Conditionals, and PHP Decision-Making - The else statement
(Page 4 of 4 )
The optional else statement (see Example 4-6) provides a default block of code that executes if the condition returned is FALSE. else cannot be used without an if statement, as it doesn't take a conditional itself. So, else and if have to always be together in your code.
Example 4-6. else and if statements
if ($username == "Admin"){
echo ('Welcome to the admin page.');
}
else {
echo ('Welcome to the user page.');
}
Remember to close out the code block from the if conditional when you've used braces to start your block of code. Similar to the if block, the else block should also use curly braces to begin and end the code.
The elseif statement
All of this is great except for when you want to test for several conditions simultaneously. To do this, you can use the elseif statement. It allows for testing of additional conditions until one is found to be true or until you hit the else block. Each elseif has its own code block that comes directly after the elseif condition. The elseif must come after the if statement and before an else statement if one exists.
The elseif structure is a little complicated, but Example 4-7 should help you understand it.
Example 4-7. Checking multiple conditions
if ($username == "Admin"){
echo ('Welcome to the admin page.');
}
elseif ($username == "Guest"){
echo ('Please take a look around.');
}
else {
echo ("Welcome back, $username.");
}
Here you can check for two conditions and take different actions based on each of the values for $username. Then you also have the option to do something else if the $username isn't one of the first two.
The next construct builds on the concepts of the if/ else statement, but it allows you to efficiently check the results of an expression to many values without having a separate if/else for each value.
Please check back next week for the conclusion to this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of the book Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Check it out today at your favorite bookstore. Buy this book now.
|
|