Following on from the previous post on IF statements.

An if statement is only executed once – if condition do this else do that. You can have more than one 'else', for example if condition, do this, else if condition, do this, else, do that.

[source:php]if (condition) {
do this
} else if (condition) {
do this
} else {
do that
}[/source]

You can have as many else if statements (elseif without a space is also allowed) as you wish however after a while the code can get out of control. A much neater way is to use a switch Statement (known to me as a case statement due to earlier programming learning!).

[source:php]$a = 2;
switch ($a) {
case "1" :
print "a is 1";
break;
case "2" :
print "a is 2";
break;
case "3" :
print "a is 3";
break;
default :
print "I gave up typing!!";
break;
}[/source]

A break statement is required at the end of each block of code here, otherwise the PHP would execute every line. break just means at that point break out of the curly brackets group you are currently in. It can be used in an if statement as well.

So just to recap:

The Ternary operator is perfect for a quick and basic if statement where you would only execute one line of code per condition. This cuts down your code and can neatly sit in between your HTML code.

The IF statement is more suited to multiple lines of code per option and to a maximum of 3 separate conditions.

The Switch / Case statement is suited to a situation where there could be more than 3 separate conditions available to meet.

Which to use and when? The Ternary operator should only really be used for the one liners. Otherwise it's down to personal choice however in my opinion once you have more than 3 elseif conditions then it is a lot easier to write and read a switch statement, it requires less coding and probably (although I couldn't say for certain without tests) executes quicker – I'm sure someone will be along soon to verify this!

Trackback URL for this post: http://www.stuffbysarah.net/2006/01/16/complex-if-statements-and-the-switch-statement/trackback/

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Latest Tweets

  • Had a busy day but feel like I've tied up a lot of loose ends of work, plus getting the ball rolling on a new job. Fun month ahead! 6 hrs ago
  • Gorgeous but cold day out there. Nappies already out on the line getting plenty of sun. Shame I have to work, great photo ops out there 19 hrs ago
  • I've just increased my Dropbox space by over 3GB for free by syncing the photos off my phone. So easy :-) 1 day ago
  • More updates...