PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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.



Comment on this Question and Answer >>>

ASK A QUESTION

More other PHP Questions

What are autoglobals?

Can I include Javascript in my PHP code?

How do I check if a date entered exists?

How do I find out about my PHP installation?

How can I stop my PHP script timing out?



Custom Search