0

I have this effective date and the array start and repeat every 12 cycles. How do I check the item value of a specific date then?

I've tried to get the item value for specific date start from the effective date but it returns no value.

<?php
$start_date = '2019-01-01';
$end_date = '2019-01-30';

$item = array('a','a','a','a','o','o','b','b','b','b','o','o');
$i = 0;

while (strtotime($start_date) <= strtotime($end_date)) {
    $i = $i+1;
    $value = $item[$i];

    if($start_date == '2019-01-05') {
    echo "Date:".$start_date." Value:".$value;
    echo "</br>";
    }
    if($start_date == '2019-01-07') {
    echo "Date: ".$start_date." Value: ".$value;
    echo "</br>";
    }
    if($start_date == '2019-01-25') {
    echo "Date: ".$start_date." Value: ".$value;
    echo "</br>";
    }

    $start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));
    }

?>

I expect the output to be like:

Date:2019-01-05 Value:o
Date: 2019-01-07 Value: b
Date:2019-01-25 Value:a

But I get:

Date:2019-01-05 Value:o
Date: 2019-01-07 Value: b
Date:2019-01-25 Value:

How to get nth value of the date every 12 cycles start from the effective date?

Nick
  • 138,499
  • 22
  • 57
  • 95
EDDY
  • 103
  • 1
  • 10

2 Answers2

1

Your problem is that you are not resetting the array index once it goes past the length of your array. You can fix that by changing:

$i = $i+1;

to

$i = ($i+1) % 12;

Note that if you had PHP error reporting enabled (see here), you would have received an "undefined offset" Notice which would have helped you find this problem.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks! I never thought to use modolus operator. It's working. For your alternative solution, how do I choose another date besides the date in the array? Let say '2019-03-01', how to get the value for this date considering the effective date for 12 cyclesvalue start from '2019-01-01'? – EDDY Sep 24 '19 at 05:54
  • 1
    The calculation of days $ day with / (24 * 60 * 60); is not correct. Not every day has 24 hours (the days when changing summer / winter time). – jspit Sep 24 '19 at 05:59
  • @jspit can't believe I forgot that. – Nick Sep 24 '19 at 06:09
  • @jspit I think it's okay because most of the country has 24 hours a day. – EDDY Sep 24 '19 at 06:10
  • @Nick yes, this is what I'm looking for. Thank you for your solution, I learned something from this. – EDDY Sep 24 '19 at 06:10
  • 1
    @jspit is correct, if you have daylight savings this code will not work. – Nick Sep 24 '19 at 06:11
1

You need not a loop. Loops are slow.

function getItem($date, $startDate){
  $item = array('a','a','a','a','o','o','b','b','b','b','o','o');
  $diff = date_create($startDate)->diff(date_create($date));
  if($diff->invert) return false; //error $date < $startDate
  return $item[$diff->days%12];
}

//example for use
$date = "2019-01-25";
$startDate = '2019-01-01';

echo getItem($date, $startDate);  //a
jspit
  • 7,276
  • 1
  • 9
  • 17