PHP Switch Statement

Submitted by: 
Visitors have accessed this post 6506 times.

Switch Statement is the same as If…Else Statements except that it is easier to use if you have multiple conditions.
Switch Syntax

  1. switch (condition)
  2. {
  3. case condition1:
  4. statement to be executed if n=condition1;
  5. break;
  6. case condition 2:
  7. statement to be executed if n=condition2;
  8. break;
  9. default:
  10. statement to be executed if n is different from both condition 1 and condition 2;
  11. }

condition is a variable expression that is evaluated once. If the first condition is true then the succeeding condition will not be executed anymore, else it will continue until it finds the condition that is equals to true or execute the default statement if no matching condition.

  1. <html>
  2. <body>
  3. <?php
  4. switch ($lastname)
  5. {
  6. case “smith”:
  7. echo "Welcome Mr. Smith";
  8. break;
  9. case “cruz”:
  10. echo "Welcome Mr. Cruz";
  11. break;
  12. default:
  13. echo "Welcome Guest";
  14. }
  15. ?>
  16. </body>
  17. </html>

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.