php resource centre

  • about
  • articles
  • tutorials
  • resources
  • certification
Home

Primary links

  • About
  • Articles
  • Tutorials
  • Resources
  • Certification

The switch Statement

admin — Tue, 05/09/2006 - 11:33am

When you want to compare the same variable or expression with many different values, and execute a different piece of code depending on which value it equals to, the “if” statement might prove to be repetitive. This is where “switch” comes in.



switch - use this statement to select one of many blocks of code to be executed.

Following is the correct switch Statement Syntax:

<?php

switch (expression) {


case "value1":
code to be executed if expression = value1;
break;


case "value2":
code to be executed if expression = value2;
break;


default:
code to be executed if expression is not equal to value1 or value2

}
?>

Like the if Statement, lines of code within the switch Statement are enclosed within curly braces. The braces define the beginning and end of the switch Statement. The following example demonstrates the use of the switch statement:

switch ($number)

{

case 1:

print "the number is 1";

break;

case 2:

print "the number is 2";

break;

case 3:

print "the number is 3";

break;

default: //if no other values are matched, do the following statement

print “the number is not equal to 1, 2 or 3”;

}

If you don’t write a “break” statement at the end of a statement group, PHP will go on executing the statements.

  • Tutorials
  • Login to post comments

User login

  • Request new password

Follow Us

Who's online

There are currently 0 users and 1 guest online.

Who's new

  • Nisha
  • linnaeus
  • Yameen
  • TalleyReedy
  • admin

Follow vipin7873 on Twitter

<!-- Start of Woopra Code -->

<!-- End of Woopra Code -->

  • about
  • articles
  • tutorials
  • resources
  • certification

copyright © 2010 Vipin Chandran