Switch is another type of conditional, best used in place of a long if-elseif-else conditional.
Switch statement selects one of many blocks of code to be executed, by comparing the value of a single variable with a succession of values.

  - Syntax:
switch ($variable) {
  case 'value1':
    // Do this
  case 'value2':
    // Run other code
    // if nothing else is true, do this
- The value of the $variable within the brackets is the item being tested.
- The switch conditional compares the value of $variable with the values for each case. When it finds a match, the block of code associated with that case is executed, up until the break. If no match is found, the default statement is executed, assuming it exists (it's optional).
The switch conditional can only check a variable's value for equality.

The break statements are optional, but if you don't use them, PHP will continue to evaluate the next case and may execute some code further down the case tree.
The default statement is used if no match is found.

- Example:
$num = 2;

switch($num) {
  case 1:
    echo 'Small number';
  case 2:
    echo 'Medium number';
  case 3:
    echo 'Bigger number';
    echo 'No number between 1 and 3';
This code will output: "Medium number".

• Another example, with a string as the value to be compared.
switch($today) {
  case 'Monday':
    echo 'Today is Monday, I go to school.';
  case 'Tuesday':
    echo 'Tuesday, lot of work to do.';
  case 'Sunday':
    echo 'Sunday, good day for rest.';
    echo 'A normal day';

Daily Test with Code Example

Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP Switch Case

Last accessed pages

  1. Read Excel file data in PHP - PhpExcelReader (63706)
  2. JavaScript Course - Free lessons (15710)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (48156)
  4. AJAX with POST and PHP (12412)
  5. Shape Tween - Flash Animation (4051)

Popular pages this month

  1. Contact page - CoursesWeb (1955)
  2. Tabs effect with CSS (1942)
  3. Insert, Select and Update NULL value in MySQL (1036)
  4. Read Excel file data in PHP - PhpExcelReader (832)
  5. PHP getElementById and getElementsByTagName (513)