在几行代码中用几天增加日期时间[关闭]

My main goal is to check if ID == From 1 to 50 or not, if yes, so i need to echo datetime based on ID, For example if ID === 5 echo $dtime['5'] and so on , i've made an array to increase days for each ID

$dtime = array(
     1  => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 0 days')),
     2  => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 1 days')),
     3  => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 2 days')),
     4  => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 3 days')),
     48 => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 47 days')),
     49 => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 48 days')),
     50 => date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+ 49 days')),
     );

and here is my if/elseif statements

if ($next_id === 1):
 echo $dtime['1'];
elseif ($next_id === 2):
 echo $dtime['2'];
elseif ($next_id === 3):
 echo $dtime['3'];
 echo $dtime['48'];
elseif ($next_id === 49):
 echo $dtime['49'];
elseif ($next_id === 50):
 echo $dtime['50'];
endif;

everything is working fine this way, BUT i believe that there is a short way to achieve my goal without all these lines, Any ideas? Thanks in advance.

to build your array -

$dtime=array();
for($i=0;$i<49;$i++){
    $dtime[$i+1] = date('Y/m/d H:i:s', strtotime($rdate['r_date']. "+ $i days"));
}

to get your value

$next_id=##;
if (array_key_exists($next_id, $dtime)) {
    echo $dtime[$next_id];
}

You can just do

echo date('Y/m/d H:i:s', strtotime($rdate['r_date']. sprintf('+ %d days', $next_id - 1)));

Constraint to valid values of $next_id is left as an exercise for the reader.

you can add key to array without if else if your next_id and condition is same

echo $dtime[$next_id];

also you can test with my output,

let me know if i can help you more.

$dtime = date('Y/m/d H:i:s', strtotime($rdate['r_date']) + ($next_id-1)*(60*60*24) );

The first step is to turn your date $rdate['r_date'] into a Unix timestamp. Then add (60*60*24), which is the number of seconds in a day. Finally, use the date() function to convert it all back to a datetime format.

if(in_array($next_id, range(1, 50))) { //if value of next_id is valid (based on condition u applied)
  echo date('Y/m/d H:i:s', strtotime($rdate['r_date']. '+'. ($next_id - 1).' days')),
}