I have an array in PHP where I store day values
$days = array (
1 => 'Mon',
2 => 'Tue',
3 => 'Wed',
4 => 'Thu',
5 => 'Fri',
6 => 'Sat',
7 => 'Sun'
);
I have a comma separated values which denote the keys of the variable $days. If the series is
1,2,3,4,5,6,7 then it should dispaly as "Mon - Sun".
1,2,3,4,5 then it should dispaly as "Mon - Fri".
1,2,4,5,6 then it should display "Mon - Tue, Thu - Sat"
1,3,5,7 then it should display "Mon, Wed, Fri, Sun"
The below code will generate only "Mon - Tue - Wed - Thu - Fri" for the series 1,2,3,4,5
$keys = "1,2,3,4,5,6";
$days = array('1' => 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
$key_array = explode(',', $keys);
$day_series = $first_day = $days[reset($key_array)];
$first_value = reset($key_array);
foreach ($key_array as $key => $value) {
if ($first_value != $value) {
if ($value == $i) {
$day_series = $day_series . ' - ' . $days[$value];
} else
$day_series = $day_series . ', ' . $days[$value];
}
$i++;
}
echo $day_series;
Remove
else
from yourforeach
loop like thisThis should work to give you
Mon-Fri
for1,2,3,4,5