Please help me, I have $repeatdays array $repeatdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
,
I do this to get next day name:
$current = 'wednesday';
$keys = array_values($repeatdays);
$ordinal = (array_search($current,$keys) 1)%count($keys);
$nextreccurence = strtolower($keys[$ordinal]);
echo $nextreccurence; // will return 'thursday'
but what if 'wednesday'
is not exist in $repeatdays
? for example $repeatdays = ['sunday', 'monday', 'tuesday', 'thursday', 'friday', 'saturday']
I do this again:
$current = 'wednesday';
$keys = array_values($repeatdays);
$ordinal = (array_search($current,$keys) 1)%count($keys);
$nextreccurence = strtolower($keys[$ordinal]);
echo $nextreccurence; // but now only return 'monday', my expected result 'thursday'
how I can get expected 'thursday'
result if 'wednesday'
is not exist in that array?
====
by the way, $repeatdays
is dynamic by user selected day that stored into $repeatdays
.
for example if today is 'wednesday'
then user selected is ['sunday', 'friday']
, then I want system to get 'friday'
,
AND if today is 'friday'
then user selected is ['sunday', 'friday']
, then I want system to get 'sunday'
,
CodePudding user response:
If you can use the php functions, then you can do this:
$dayoftheweek = "wednesday"; // or however you populate it
$timestampday = strtotime($dayoftheweek);
echo date('l', strtotime(" 1 day", $timestampday));
CodePudding user response:
One solution would be to have a second, reference array with all the days, where you could look up next days until you'll find one that is available also in $repeatdays
.
One not perfect implementation would be:
<?php
function get_next_day($current)
{
$reference = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
$current_key = array_search($current, $reference);
$next_key = ($current_key 1) % count($reference);
return $reference[$next_key];
}
function search_for_available_next_day($current, $repeatdays)
{
$next = $current;
do {
$next = get_next_day($next);
}
while (!in_array($next, $repeatdays));
return $next;
}
var_dump(search_for_available_next_day('wednesday', ['sunday', 'friday']));
var_dump(search_for_available_next_day('friday', ['sunday', 'friday']));
var_dump(search_for_available_next_day('thursday', ['sunday', 'friday']));
var_dump(search_for_available_next_day('saturday', ['sunday', 'friday']));