How To

How to Write a Switch Statement in PHP

Member
By Mike
User-Submitted Article
(0 Ratings)

You could write a series of "IF" statements to drill down through a variable value to act up the condition that you were looking to execute. However the swtich statement is much easier and a whole lot cleaner.

Here is how you write a switch statement in PHP.

Difficulty: Easy
Instructions
  1. Step 1

    For the sake of this tutorial all code will be displayed in a picture associated with each step. eHow does not allow code to be written within step. So the first step is to launch your PHP editor to get started.

  2. Step 2
     

    First we open up our switch statement by defining what exactly we are testing on:

    switch (variable conditional) {

    we write in the word "switch" followed by an open parenthesis the variable we are testing the condition of, followed by a closed parenthesis, and then the open curly brace which lets the compiler know the code to follow is part of the switch statement.

  3. Step 3
     

    Next we have to set up some conditions. That lookes like this:
    case "value":
    break;

    we type in the word "case" followed by the value we are looking for followed by a colon. Everything after that colon will be executed until it hits the keyword "break;" or until it hits the closing curly brace. So if you do not want all of the cases executed you will need to add the keyword "break;".

  4. Step 4
     

    The final optional value you can put into your switch statement is called "deafult:". This is a catch all for any other value that you do not have a case for. If you have been following the code in the pictures associated with each step, you will see that the variable is set to 3, but there is no case for 3, therefore we can put in the word default to handle it.

Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Computers Newsletters

Copyright © 1999-2010 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US † requires javascript

eHow Computers
eHow_eHow Technology and Electronics