Tuesday 15 April 2008

using CASE instead of If and ELSEIF

Using Switch instead of If and Elseif


I have a script that is being giving the month as a value and I would like to return the value of the month in text - ie January.



So here's the code in the most obvious hack

$month= date('m');



if ($month == 1 ) {
$month= 'January';
}
elseif ($month == 2 ) {
$month= 'February';
}
elseif ($month == 3 ) {
$month= 'March';
}
elseif ($month == 4 ) {
$month= 'April';
}
elseif ($month == 5 ) {
$month= 'May';
}
elseif ($month == 6 ) {
$month= 'June';
}
elseif ($month == 7 ) {
$month= 'July';
}
elseif ($month == 8 ) {
$month= 'August';
}
elseif ($month == 9 ) {
$month= 'September';
}
elseif ($month == 10 ) {
$month= 'October';
}
elseif ($month == 11 ) {
$month= 'November';
}
elseif ($month == 12 ) {
$month= 'December';
}

>>>>

it's in my understanding that using switch should tidy this code up somewhat.

http://uk.php.net/manual/en/control-structures.switch.php

my statement should then look like this.


switch ($month) {

case 1:
$month= 'January';
break;
case 2:
$month= 'February';
break;
case 3:
$month= 'March';
break;
case 4:
$month= 'April';
break;
case 5:
$month= 'May';
break;
case 6:
$month= 'June';
break;
case 7:
$month= 'July';
break;
case 8:
$month= 'August';
break;
case 9:
$month= 'September';
break;
case 10:
$month= 'October';
break;
case 11:
$month= 'November';
break;
case 12:
$month= 'December';
break;

}

No comments: