TaG
TaG

Reputation: 9

Translate numeric month value into month name

How do I show the dates number format next to its name in the array using PHP? So that the number format is saved in the database and the month name is displayed?

Here is the php code.

$month_options = array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

Upvotes: 0

Views: 321

Answers (3)

eswald
eswald

Reputation: 8406

If you're using the native date type of your database, you're probably getting back a string like '2010-04-07'. To get a timestamp from that, use strtotime(). That timestamp can then be passed to the date() function. The F format character gives you the month name, without having to use a $month_options array.

$when = get_date_field_from_database();
$timestamp = strtotime($when);
$month = date('F', $timestamp);

Upvotes: 1

code_burgar
code_burgar

Reputation: 12323

If I understand what you are trying to do this will help:

$month_options = array( 1 => "January", 
                        2 => "February",
                          ... snip ...
                        12 => "December");

echo $month_options[2]; // echoes February

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

If your month's number is stored in a variable, you can use it to access the right item in your array., using a syntax such as $array[index].


For example, the following portion of code :

$month_options = array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$month_num = 3;

echo $month_options[$month_num];

would give you :

March

Note that, in PHP, array indexes start at 0 -- which means that the item with the index 3 is actually the fourth item in the array.


Here, though, the first item in the array is not quite useful : it's a month -- so, you could remove it -- and you'd have to add 1 to the index used to point to the right month :

$month_options = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$month_num = 3;

echo $month_options[$month_num + 1];


And you might to go through the array section of the PHP manual ;-)

Upvotes: 2

Related Questions