Use of switch and case in php and codeigniter
16,684
I think your echo
needs to be outside of the switch
as well... checking to verify.
Yep, the echo needs to be outside. The type should actually be coerced when comparing.
<?php
$s = '5';
switch ($s) {
case 5:
echo "Foo\n";
break;
default:
echo "Bar\n";
break;
}
echo $s;
OUTPUT
Foo
5
And for your example:
<?php
function indicators() {
$Year = '1355';
$Month = '03';
switch ($Year) {
case 1354:
$key=array('0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6');
$output = $key[$Month-1];
break;
case 1355:
$key=array('0.6','0.7','0.2','0.4','0.7','0.1','0.7','0.2','0.5','0.9','0.4','0.8');
$output = $key[$Month-1];
break;
}
echo $output; // The output should be: 0.7
}
indicators();
OUTPUT
0.2
Which is correct according to the code. '03' - 1 == 2
. $key[2] == '0.2'
As pointed out in the comment below by @vstm, the docs state that the "switch/case does loose comparision."
Author by
jennifer Jolie
Updated on June 04, 2022Comments
-
jennifer Jolie almost 2 years
I want use of
switch
andcase
in php and codeigniter library, i try it as following code, But I not receive output. what do i do?Demo: http://codepad.viper-7.com/Wq0Noj
function indicators() { $CI = &get_instance(); $Year = '1355'; $Month = '03'; switch ($Year) { case 1354: $key=array('0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6'); $output = $key[$Month-1]; break; case 1355: $key=array('0.6','0.7','0.2','0.4','0.7','0.1','0.7','0.2','0.5','0.9','0.4','0.8'); $output = $key[$Month-1]; break; echo $output; // The output should be: 0.7 } }
-
vstm over 11 yearsYep,
switch
does "loose comparison" as documented in the... documentation.