Papa De Beau
Papa De Beau

Reputation: 3828

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);

Upvotes: 0

Views: 262

Answers (3)

meyer9
meyer9

Reputation: 1140

Try using str_pad.

$a = str_pad($a, 2, "0", STR_PAD_LEFT)

Upvotes: 2

Jhecht
Jhecht

Reputation: 4435

Hammered out some quick code, but jmeyer2k beat me to it. I figured I'd post what I'd written as it's a little more complete and gives some context

function days_in_month($year){
    $data = array();

    for($i=1; $i<=12; $i++){
        $num = cal_days_in_month(CAL_GREGORIAN, $i, $year);
        for($a=1; $a<=$num; $a++){
            $a = str_pad($a,2,"0",STR_PAD_LEFT);
            $data[] = str_pad($i,2,"0",STR_PAD_LEFT).$a.$year;
        }
    }
    return $data;
}

I haven't tested it, so it may be a little buggy (currently working from a different machine than regular)

Upvotes: 1

John Conde
John Conde

Reputation: 219804

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.

Upvotes: 4

Related Questions