0

I'm trying to build an array of days using date(z) days of year format, starting with today, and stepping through a set number of days.

I've figured out a solution to this, but it doesn't feel like it's the most efficient, maybe there is a built-in function in PHP for this.

Current solution:

$today = date(z);
$count = 3;
$array = array();
$i = 0;
while ($i < $count) {
  $array[] = $today + $i;
  $i++;
}

print_r($array);

Outputs correctly to this: Array ( [0] => 297 [1] => 298 [2] => 299 )

Any other better solutions?

3
  • I wouldn't call this a bad approach. Maybe a for loop would be better than the while. Commented Oct 25, 2018 at 16:20
  • What's the desired behavior when $count is high enough to cross years? Commented Oct 25, 2018 at 16:22
  • @PatrickQ hadn't considered it, in my use case that would not be possible. Commented Oct 25, 2018 at 16:31

1 Answer 1

3

you could use range - https://secure.php.net/manual/en/function.range.php

range — Create an array containing a range of elements

So let's take today:

$today = date('z');
$range = range($today, $today + $count);
Sign up to request clarification or add additional context in comments.

2 Comments

Would range($today, $today+$count); (or similar) be better?
@NigelRen thanks for that; for my use case I need the array ONLY to have the days specified, not the entire 365 so this would work better.

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.