Ralph E. Emeka Ralph E. Emeka - 1 month ago 16
PHP Question

Formatting month names as alphabets

I am trying to create an associative array that will parse an alphabet for each month name. e.g JAN - A, FEB - B, MAR - C... I need some help for this. I have done a lot of searching but not able to. Can anyone help please?
Thanks in advance.

<?php
$my_month = date('m');
$months = array("JAN"=>"A",
"FEB"=>"B",
"MAR"=>"C",
"APR"=>"D",
"MAY"=>"E",
"JUN"=>"F",
"JUL"=>"G",
"AUG"=>"H",
"SEP"=>"I",
"OCT"=>"J",
"NOV"=>"K",
"DEC"=>"L" );

if ($my_month == date('M')) {
echo $months[$my_month];
} else {
echo 'almost there';
}

?>

Answer

The code you need to create an array as you want is this:

$months['1'] = 'A';
$months['2'] = 'B';
$months['3'] = 'C';
$months['4'] = 'D';
$months['5'] = 'E';
$months['6'] = 'F';
$months['7'] = 'G';
$months['8'] = 'H';
$months['9'] = 'I';
$months['10'] = 'J';
$months['11'] = 'K';
$months['12'] = 'L';

Or even better:

$months = array("1"=>"A",
                "2"=>"B",
                "3"=>"C",
                "4"=>"D",
                "5"=>"E",
                "6"=>"F",
                "7"=>"G",
                "8"=>"H",
                "9"=>"I",
                "10"=>"J",
                "11"=>"K",
                "12"=>"L" );

And let's say the $my_month variable has the month (in the form 'JAN', 'FEB', ...) from which you want to get the corresponding letter. This is what you write to get the letter:

echo $months[$my_month];