Search code examples
phpdatestrlen

PHP if only 1 character - Get All Days In a Year


I am trying to see if a var is only 1 character and if so I will add a 0 before it.

I would think if(strlen($a)==1) but it does not. Below is my full code.

In short what I am trying to do is get all of the days of the year and put any given year in an array in this format.

Month Day Year like this 010115 that would be January 1st 2015. Then i would like to put the whole year in an array; All 365 days in any given year. Hard coded it would look like this

$AllDaysIn2015= array(010115, 010215, 010315, 010415, 010515, etc... );

But how would I get all of them into one array in this format?

To achieve this I am starting here but got stuck on counting the 1 character.

function daysInMonth($year)
{
    for($i = 1; $i < 12; $i++)
    {
    $num = cal_days_in_month(CAL_GREGORIAN, $i, $year); // 31
    echo $num . "<br>";
        for($a =1; $a < $num+1; $a++)
        {
            $a = trim($a);
            if(strlen($a)==1)
            {
            $a = "0$a";
            }
            else
            {
                echo "$a, ";
            }


        }
    echo "<br>";
    }
}

daysInMonth(2014);

Solution

  • Untested:

    <?php
    function daysInMonth($year) {
        $dates = array();
        for($i = 1; $i <= 12; $i++) {
            $num = cal_days_in_month(CAL_GREGORIAN, $i, $year); 
            for($a = 1; $a < $num+1; $a++) {
                $dates[] = sprintf('%02d%02d%04d', $i, $a, $year);
            }
        }
        return $dates;
    }
    
    $datesInYear = daysInMonth(2014);
    

    This uses sprintf() to handle the formatting for you. No need to check the length of the number.