PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

I have lots of if else logic - is there another option?


Of course there is! What you need is the switch statement. This is a clearer way of writing your code with lots of different options.

So rather than having loads of if, else or if, elseif, else loops, you can have it all neatly ordered with a switch statement.

Let's take a look shall we:

<?php
switch($baggage) {
case 
'booze':
echo 
"You have something to declare!";
break;
case 
'candy':
echo 
"You have a sweet tooth!";
break;
case 
'water':
echo 
"You can't take liquid on board this flight, ma'am!";
break;
default:
echo 
"Could anyone have interfered with your baggage?";
break;
}
?>


You should be able to work out what will happen here very clearly and it's easy to write, much better than convoluted if-elseif-if conditionals.

The key points to note are:

Each option for the variable, here $baggage, is started with the word 'case' then the value, then a colon, then the relevant code, here echo statements, and then 'break;'.

The other important point is the use of a default at the bottom, if no other case applies above (get the 'baggage' joke yet?), then the default will run.



More other PHP Questions

How do I find the timestamp for a particular date?
How do I define a constant in PHP?
How can I add branching logic to my PHP code?
What is a constant in PHP?
Can PHP create PDF files for me?