Reputation: 1859
I am just a beginner in php. I am trying to print the array of months using the following code.
<?php
$totalmonth=12;
for($startmonth=01; $startmonth<=$totalmonth; $startmonth++)
{
$montharr[]=$startmonth;
}
print_r($montharr);
?>
My result is Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 [10] => 11 [11] => 12 )
I need my result should look like this
[0] => 01 [1] => 02
How can i do that?
Upvotes: 0
Views: 104
Reputation: 15897
You could use sprintf to print it to a string as zero-padded integers.
Example:
<?php
$month = sprintf("%02d", $month);
due to the nature of integers, math; PHP (and the majority of all applications) will interpret (int)01
as 1
. To keep the leading zero, it has to be a string.
Upvotes: 1
Reputation: 1969
Force that a String is inserted, by implicitly converting it into one:
$montharr[]= "" + $startmonth;
Upvotes: 0
Reputation: 693
Use PHP built-in str_pad:
<?php
$totalmonth=12;
for($startmonth=01; $startmonth<=$totalmonth; $startmonth++)
{
$montharr[] = str_pad($startmonth, 2, '0', STR_PAD_LEFT);
}
print_r($montharr);
?>
Upvotes: 0
Reputation: 72975
Use str_pad.
<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
$montharr[]=str_pad($startmonth, 2, "0", STR_PAD_LEFT);
}
print_r($montharr);
?>
Upvotes: 3
Reputation: 2870
For example sprintf
: http://php.net/manual/en/function.sprintf.php
Upvotes: 0
Reputation: 34837
PHP has many date functions that will probably serve better solutions to whatever you're trying to achieve, but a very quick and dirty way would be to check if the number is lower then 10 and then prepend a zero:
<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
// Check amount
if($startmonth < 10) {
$montharr[]='0'.$startmonth;
} else {
$montharr[]=$startmonth;
}
}
print_r($montharr);
?>
Upvotes: 0