PHP switch statement examples 

Joined:
03/10/2011
Posts:
84

May 16, 2011 19:50:19    Last update: May 16, 2011 20:05:42
In PHP switch statement:
  1. An integer is considered equal to the corresponding string and vice versa.
  2. Boolean true equals any value considered true, for example, 'a'.
  3. Boolean false equals any value considered false, for example, '0'.
  4. Arrays are compared value by value.


The following PHP switch example:
<?php
$b = array(1, 2);
$a = array('a', 'b', 1, 2, true, false, array(1, '2'), $b);

foreach ($a as $i) {
    echo "loop variable: ";
    var_dump($i);
    switch ($i) {
	case 'a':
	    echo "case 'a'\n\n";
	    break;

	case 'b':
	    echo "case 'b'\n\n";
	    break;

	case '0':
	    echo "case '0'\n\n";
	    break;

	case '1':
	    echo "case '1'\n\n";
	    break;

	case $b:
	    echo "case \$b\n\n";
	    break;

	case 2:
	    echo "case 2, no break falls thru to next case\n";

	default:
	    echo "The default case\n\n";
    }
}
?>


Outputs:
loop variable: string(1) "a"
case 'a'

loop variable: string(1) "b"
case 'b'

loop variable: int(1)
case '1'

loop variable: int(2)
case 2, no break falls thru to next case
The default case

loop variable: bool(true)
case 'a'

loop variable: bool(false)
case '0'

loop variable: array(2) {
  [0]=>
  int(1)
  [1]=>
  string(1) "2"
}
case $b

loop variable: array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
case $b


In alternative syntax:
<?php
$b = array(1, 2);
$a = array('a', 'b', 1, 2, true, false, array(1, '2'), $b);

foreach ($a as $i):
    echo "loop variable: ";
    var_dump($i);
    switch ($i):
	case 'a':
	    echo "case 'a'\n\n";
	    break;

	case 'b':
	    echo "case 'b'\n\n";
	    break;

	case '0':
	    echo "case '0'\n\n";
	    break;

	case '1':
	    echo "case '1'\n\n";
	    break;

	case $b:
	    echo "case \$b\n\n";
	    break;

	case 2:
	    echo "case 2, no break falss thru to next case\n";

	default:
	    echo "The default case\n\n";
    endswitch;
endforeach;
?>

Share |
| Comment  | Tags