0

I need to write an array that looks like this:

$years = array('12', '11', '10', '09', '08');

I would like to have a script that will create this array, so that I don't have to update it every year.

Tried this:

for ($i = date("y"); $i >= 08; $i++) {
    $yrs .= '"'.$i.'", ';
}

$years = array($yrs);

3 Answers 3

1

You want to decrement in your loop instead of increment, since you are trying to go from 12 down to 8. So change your ++ to --. You can also append to an array using the $years[] = ... notation, and make an array using $years = array():

$years = array();
for ($i = date("y"); $i >= 8; $i--)
    $years[] = str_pad($i, 2, "0", STR_PAD_LEFT);

print_r($years) gives:

Array
(
    [0] => 12
    [1] => 11
    [2] => 10
    [3] => 09
    [4] => 08
)

Example: http://codepad.viper-7.com/VDQNj2

Sign up to request clarification or add additional context in comments.

4 Comments

It looks great but I get an array all the way to year 2000. Can I stop it at 2008 (08)?
Just a note, in your example the loop should stop at 08, but doesn't because you prefixed the number 8 with a zero, causing it to be interpreted as an octal number. However, since 8 is an invalid digit for an octal number, it gets converted to the integer value 0. To fix it, just remove the 0! :)
Yes sorry, I had it right in my answer, but wrong in that codepad link for some reason. Here is a new codepad: codepad.viper-7.com/BOktOr Thanks @nickb
@user1131166 See my reply to nickb :)
0
$years = array();

for ($i = date("y"); $i >= 8; $i--) {
    $years[] = substr("00".$i,-2);
}

1 Comment

@user1 I just stole the $i-- from you - just mentioning it so pls accept user1's answer
0

PHP's range function helps out a lot here:

4-digit years

$thisYear = date('Y'); // "2012"
$years = range($thisYear, $thisYear-4);

// array(2012,2011,2010,2009,2008)

2-digit years

$thisYear = date('y'); // "2012"
$years = range($thisYear, $thisYear-4);

// array(12,11,10,9,8)

+ adding zero-padding to 2-digit years

$years = array_map(function($year) {
    return sprintf('%02u', $year);
}, $years);

// array("12","11","10","09","08")

Note: The use of an inline function (closure) for array_map requires PHP 5.3+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.