Re: switch case - to require the break statements seems strange to me

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Govinda schreef:
Not that it is an issue, but just to understand the logic-
Why do we have to use 'break' statements in each case?

switch ($i) {
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
}

all 3 cases fire, even though $i only equals ONE of those case values (if I said that right). I mean if $i==1, then in other languages I don't expect the first or last case to fire! (?) Is the purpose just so one has the OPTION of letting them all fire, and turning that off with 'break'?

pretty much, all code will be run inside the switch after the first case
found to equate (match) until a break is hit. try it:

foreach (range(0,2) as $i) {
	echo "\$i = $i -- running switch ... \n";
	switch ($i) {
		case 0:
			echo "first case\n";
		case 1:
			echo "second case\n";
		case 2:
			echo "third case\n";
	}
}

Or is there a better reason?

-G



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux