05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A switch statement is given an expression and compares its value to all cases in the<br />

switch; all statements in a matching case are executed, up to the first break keyword<br />

it finds. If none match, and a default is given, all statements following the default<br />

keyword are executed, up to the first break keyword encountered.<br />

For example, suppose you have the following:<br />

if ($name == 'ktatroe')<br />

// do something<br />

elseif ($name == 'rasmus')<br />

// do something<br />

elseif ($name == 'ricm')<br />

// do something<br />

elseif ($name == 'bobk')<br />

// do something<br />

You can replace that statement with the following switch statement:<br />

switch($name) {<br />

case 'ktatroe':<br />

// do something<br />

break;<br />

case 'rasmus':<br />

// do something<br />

break;<br />

case 'ricm':<br />

// do something<br />

break;<br />

case 'bobk':<br />

// do something<br />

break;<br />

}<br />

The alternative syntax for this is:<br />

switch($name):<br />

case 'ktatroe':<br />

// do something<br />

break;<br />

case 'rasmus':<br />

// do something<br />

break;<br />

case 'ricm':<br />

// do something<br />

break;<br />

case 'bobk':<br />

// do something<br />

break;<br />

endswitch;<br />

Because statements are executed from the matching case label to the next break keyword,<br />

you can combine several cases in a fall-through. In the following example,<br />

“yes” is printed when $name is equal to “sylvie” or to “bruno”:<br />

switch ($name) {<br />

case 'sylvie': // fall-through<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Flow-Control Statements | 49

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!