0

I'm using the following PHP code to show a different text (just one) every week:

<?php

$items = [

[
'start' => '2020-02-03',
'end' => '2020-02-09',
'html' => 'Text #1'
],

[
'start' => '2020-02-10',
'end' => '2020-02-16',
'html' => 'Text #2'
],

[
'start' => '2020-02-17',
'end' => '2020-02-23',
'html' => 'Text #3'
],

];

$currentDate = date('Y-m-d');

foreach ($items as $item) {
   if ($currentDate >= $item[start] && $currentDate <= $item[end]) echo $item[html];
}

It works. But is there a better (i.e. cleaner, faster) way to achieve the same result? Is loop really necessary? Thanks.

UPDATE

Inspired by Progrock's answer (which I thank), I would modify my code as follows:

$items =
[
    '06' => 'Text #1',
    '07' => 'Text #2',
    '08' => 'Text #3',
    '09' => 'Text #4'
];

$date = new DateTime(date('Y-m-d'));
echo $items[$date->format('W')];

I think it's a better solution (for what I need).

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21

2 Answers2

0

https://www.php.net/manual/en/function.array-filter.php

$currentDate = date('Y-m-d');

$filteredItems = array_filter($items, function($item) use ($currentDate) {
    return $currentDate >= $item['start'] && $currentDate <= $item['end'];
});

Though, you're still going to have to loop the filtered items for output, eventually.

HorusKol
  • 8,375
  • 10
  • 51
  • 92
  • After this filter, you are left with the difficulty of extracting the html attribute. Which shows the OP's foreach is clearer and easier. – Progrock Feb 24 '20 at 00:52
  • ideally, the filteredItems would be passed as a variable to a view template somewhere else - I wouldn't be filtering and echoing the output in the same place... – HorusKol Feb 24 '20 at 01:06
0

As your ranges are monday->sunday you could use ISO-8601 week numbering. Though here the data is harder to interpret without comments.

<?php
$items =
[
    '06' => 'Text #1',
    '07' => 'Text #2',
    '08' => 'Text #3'
];
$iso_week = date('W', strtotime('2020-02-12'));
echo $items[$iso_week];

Output:

Text #2
Progrock
  • 7,373
  • 1
  • 19
  • 25
  • That's not a bad idea. But I would use DateTime to get the week number. Thanks! – AbsoluteBeginner Feb 24 '20 at 09:29
  • @AbsoluteBeginner your original example used `date`. So that's here. `strtotime` is there for concrete input and output in the example, just omit the second argument and it will substitute`time()` for the current timestamp. What does a `DateTime` object buy you instead? – Progrock Feb 24 '20 at 10:56
  • Mine is not a criticism to your solution. In the meantime, I've found this: https://stackoverflow.com/a/9567769/10668052. So, I would correct my own code. Your answer is perfect. – AbsoluteBeginner Feb 24 '20 at 11:16
  • @AbsoluteBeginner how does that linked solution/approach help you, how will you use it, I'm curious? – Progrock Feb 24 '20 at 11:43