Decision Making using PHP Switch Statement

Hi,

Here is a good shepherd with his sheep again :)

Today I am going to discuss Switch Statement. The basic concept of Switch is similar to the IF-ELSE statement; it helps you to write decision making code just like IF-ELSE but it is a little more organized, elegant and handy when dealing with complex logics as compare to IF-ELSE.

Remember, you can convert every IF-ELSE programme to Switch syntax but vice versa is not possible in some situations.

Remember one more thing, it is not necessary to convert IF-ELSE to Switch and vice versa, just use whatever suits to your needs, though when handling the complex and large decision making code I would suggest to use Switch.

Let’s have a look at its syntax.

Switch Statement Syntax:


switch (input)
{
case condition1:
code to be executed if input = condition1;
break;
case condition2:
code to be executed if input = condition2;
break;
default:
code to be executed
if input is different
from both condition1 and condition2;
}

Explanation:

the parenthesis of Switch accepts a value which is matched with cases and if any case if found true the block of code for that case is executed. If the input doesn’t match with any of the cases then the code block under ‘default’ is executed.

every case is headed by keyword ‘case’ following by its value and a colon (:). Every case ends with a break statement.

What is break statement: break statement breaks the flow of a certain code block in which it resides and take the control out of the block. You can use break without switch statement too for example to take the control out from a FOR loop (will discuss later) or IF statement.

Let’s write a simple programme to understand the use of Switch statement in PHP.


<?php
 
$site = "Fast Creators";
 
switch ($site)  {
 
    case "Fast Creators":
     echo "<a href="http://fastcreators.com">www.fastcreators.com</a>";
    break;
 
    case "How To Forge":
     echo "<a href="http://howtoforge.com">www.howtoforge.com</a>";
    break;
 
    case "PHP Official Site":
     echo "<a href="http://php.net">www.php.net</a>";
    break;
 
default:
  echo "Input did not match with any case";
 
  }
?>

Here we have hard-coded $site value so the first case will stand true and the programme will display www.fastcreators.com and the break statement of case will take out the control from Switch body. ‘Default’ does not require any break statement as it is the last option of the switch statement.

Switch statement’s body starts and closes with braces.

Assignment:

Make a form that has different countries names in a drop-down list. After you select a country and submit the form the accepting page should use Switch statement to check the country name and then display its Capital, Currency Name and National Language.

You can post your assignments on haroon[at]fastcreators[dot]com.

Till we gather on another article take good care of yourself and keep practicing.

- Haroon Ahmad

21 Comments

  1. caedes said,

    February 8, 2007 at 2:34 pm

    Another utilisation of switch is :

    switch (true) {
    case ($foo == $bar):
    print($foo);

    }

  2. caedes said,

    February 8, 2007 at 2:35 pm

    Another utilisation of switch is :

    switch (true) {
    case ($foo == $bar):
    print($foo);
    break;
    case ($foo == 0):
    print($bar);
    break;
    }

  3. tedd said,

    February 9, 2007 at 8:24 pm

    Hi,

    The “input” portion of your switch statement can be used, or not. All case conditions are tested on their truth and not necessarily compared to “input”.

    Try it, you’ll see that I am right.

    Cheers,

    tedd

    PS: I’ve never used the ELSE-IF statement.

  4. haroon.ahmad said,

    February 9, 2007 at 8:53 pm

    Hi Tedd,

    of course you will need INPUT for switch statement otherwise you cannot reach switch cases… INPUT that is coming in the switch statment in fact initiate the switch statement block and cases are matched then like Caedes posted in his comment.

    however programmers also send variables through INPUT and use them in CASE conditions.

  5. tedd said,

    February 9, 2007 at 11:41 pm

    You said:

    “the parenthesis of Switch accepts a value which is matched with cases and if any case if found true the block of code for that case is executed.”

    My point was that you don’t need an input “variable” to be evaluated in the case statements that follow. For example,

    switch(1)
    {
    case 1==2:
    echo(”never);
    break;

    case 2==2:
    echo(”always”);
    break;

    case 3==3:
    echo(”never);
    break;
    }

    The entire statement is based upon truth values.

    tedd

  6. haroon.ahmad said,

    February 10, 2007 at 10:25 am

    Tedd I agree with you and I understand your point.. we are talking about two different usages of switch statement input section. you can either place true / 1 (which also means true) in the input of switch and this will make switch body to be executed and then all the case matching process will go on.

    readers must understand that switch input section is like IF statement, if it gets any value other than 0 (which means false) it will execute its body..

    so Tedd has shown you a method to get into the body of switch statement by passing true value to the switch input..

    I have told you another use of switch input and that is to pass some values to it and then use it in the case making for example.

    $name=”haroon”;
    switch($name) {
    case ($name == “tedd”):
    echo “thanks for your supportive comments for all readers”;
    break;
    case ($name == “haroon”):
    echo “thanks for your nice article :) ”;
    break;
    default:
    echo “thanks for reading all these articles”;
    }

  7. Jehzeel Laurente said,

    February 22, 2007 at 4:41 am

    wow! now i understand more about the PHP switch statement compared to http://w3schools.com

    It’s a very nice explanation indeed… I’ll try to make the assignment.. :)

  8. Jehzeel Laurente said,

    February 22, 2007 at 5:15 am

    about the assignment. using a mysql database is prohibited? all data should be in the script i guess? Am I right? Hoping for your reply soon… :)

  9. haroon.ahmad said,

    February 22, 2007 at 9:21 am

    Hi Jahzeel

    Yeah, for now the MySQL database is prohibited because I am writing these articles in a series and I am going from scratch to super expert level step by step. For now you should do this assignment without MySQL however if you already have worked in MySQL then go ahead and give it a try. I will soon start PHP-MySQL portion and after that PHP-XML, PHP-Flatfiles (text files), PHP-cURL, PHP-SOAP, PHP-AJAX , PHP-WDDX-Python / PERL etc etc so your time will come to give a shot to PHP with MySQL :)

    - Haroon Ahmad

  10. Jehzeel Laurente said,

    February 22, 2007 at 9:37 am

    hey!!! i have finished the assignment.. you’re tutorial is very very nice indeed and i’m learning a lot! ^__^

    by the way, it’s not Jahzeel but Jehzeel ^__^

    w8 i’ll send my finished code to your email for comments so that I’ll learn more and more from you ^__^

    weeeeeeeee!!!

  11. Mike_G said,

    February 25, 2007 at 10:01 pm

    Hi - I’m trying to pass more than one piece of information (3 total) from a menu button to a php switch/case, and I’m not sure of the syntax . I’m passing the $page, $current, and $sub.

    My button link is:

    There is no path, since this would all happen on the index page.

    The switch/case to catch this information is:

  12. haroon.ahmad said,

    February 25, 2007 at 11:32 pm

    Hi Mike,

    You didnt provide any code. anyway, you can simply use $_GET global array to access the variables from your URL similalry use $_POST for post array. also you can just use 1 / true in the switch parenthesis like

    switch(1) {

    //use $_GET here to access your three vars
    }

    hope it will help

  13. Rhyan said,

    July 30, 2008 at 12:34 pm

    Hi guys I need some help? I’m trying to create a dynamic kind of switch can somebody help me please……………. pls. email me thanks.

  14. haroon.ahmad said,

    July 30, 2008 at 12:47 pm

    Rhyan, explain your problem in details please.

  15. Rhyan said,

    July 30, 2008 at 1:52 pm

    thanks man. Well I want to make a kind of a dynamic switch, means the choices or the function will come from my database? is that possible?

  16. haroon.ahmad said,

    July 30, 2008 at 2:31 pm

    yes that is possible. you can send any value, whether coming from database, xml document or hard-coded, to switch statement and then perform action based on cases.

  17. Rhyan said,

    July 30, 2008 at 2:53 pm

    switch($dl)
    // {
    // case NULL : echo ‘Select a location to visit the nearest Sub-zero and Wolf showroom.’; break;

    // if (mysql_num_rows($result_szwf) > 0) // yes
    // {
    // while($row = mysql_fetch_assoc($result_szwf))
    // {
    // $dll = $row[’lxsdealer_id’];
    // echo ‘case ‘.$dll.’ : ‘.$dll.'’;
    // echo ‘Country :’.$row[’lxsdealerinfo_title’].'’;

    // echo ‘Company :’;

    // echo ‘Location :’;

    // echo ‘Telephone :’;

    // echo ‘Email :’;

    // echo ‘Map :’;

    // break;
    // }
    // } else { echo “No rows found!”; // no print status message
    // }
    // }

  18. Rhyan said,

    July 30, 2008 at 3:12 pm

    Here’s the code that im trying, sorry I’m just a newbie in php. Thanks man

  19. haroon.ahmad said,

    July 30, 2008 at 3:18 pm

    what error do you get?

  20. Rhyan said,

    July 30, 2008 at 3:47 pm

    That’s the error I got.
    (Parse error: syntax error, unexpected T_CASE)

    Thanks man for helping to solve this.

  21. haroon.ahmad said,

    July 30, 2008 at 3:57 pm

    in fact you are making it really hard for me to help you. Your code is all commented, you are using double slashes in front of code. So I am not sure which line is throwing error.

    Anyway, if I consider that you are using all code you have pasted then you are doing lots of mistakes. I guess you are mixing PHP IF ELSE within Switch body and a big chunk of code is outside any CASE BREAK pair within the Switch statement. That’s why lots of things are doubtful in your code and I am not sure how to help you fix your this code.

    What I can do for you is to guide you quickly with few tips,

    1 - do not write any code outside case-break section
    2 - do not use echo to print CASE, as you are doing it in start of your code.
    3 - read my article carefully and see how PHP switch works actually and rewrite your code.

    I hope it helps.

Post a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word