Jump to content

[SOLVED] Array for Months of the Year


Omzy

Recommended Posts

Basically I have a months array:

 

$months=array('01'=>'Jan', '02'=>'Feb', '03'=>'Mar', '04'=>'Apr', '05'=>'May', '06'=>'Jun', '07'=>'Jul', '08'=>'Aug', '09'=>'Sep', '10'=>'Oct', '11'=>'Nov', '12'=>'Dec');

 

And I use a foreach loop to access this array and generate the markup as follows:

 

echo '<option value="'.$index.'"'>'.$value.'</option>';

 

As you can see the <option> VALUE attribute is 2 digits, which is why I've had to create the array with the 2 digit numbers as the index. Can this be done in a more simpler way?

Link to comment
https://forums.phpfreaks.com/topic/177106-solved-array-for-months-of-the-year/
Share on other sites

i guess you could use str_pad(), like so

$arr = array("jan", "feb", "mar","april");
foreach($arr as $key=>$value){
echo '<option value="'.str_pad((int)($key+1), 2, '0', STR_PAD_LEFT).'">'.$value.'</option>';
}

 

but thats not much better... if you already have it, and it works just use it

 

oops slight edit

Hi

 

Very similar to the above, and again not really simpler than your original:-

 

<?php
$months=array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
for($iCnt = 1 ; $iCnt <= 12 ; $iCnt++)
{
echo '<option value="'.sprintf('%02d',$iCnt).'">'.$months[$iCnt - 1].'</option><br />';
}
?>

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.