How to hide saturday and sunday in PHP array

Viewed 97

I want to hide Saturday and Sunday in PHP.

I´ve build the following code:

$begin = new DateTime($row['date']);
$end = new DateTime($row['dateul']);
$end = $end->modify( '+1 day' ); 

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
    $array[] = $date->format("Y-m-d");
}

Until here the code is working but it outputs the complete week/days in this daterange. I found this code:

if (strcasecmp($daterange, 'Sun') != 0
         && strcasecmp($daterange, 'Sat') != 0){

     }

Do I understand it right, that if value = 1 it will output Saturday for example?

Because the main idea was the following: if day for example sunday = 0 hide it in array, if sunday=1 show it in array. The values are coming from MySQL.

1 Answers

You can use the N format for DateTime::format to check the day of week, it returns 6 for Saturday and 7 for Sunday, so as long as the value is less than 6, add it to the array:

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$array = array();
foreach($daterange as $date){
    if ($date->format('N') < 6) {
        $array[] = $date->format("Y-m-d");
    }
}

Demo on 3v4l.org

Update

Based on comments from the OP, days to be included have $row[<dayname>] = 1. In that case, you can use this foreach loop, using l format to get the full day of week name and strtolower to convert to lowercase to use as an index into $row:

foreach($daterange as $date){
    if ($row[strtolower($date->format('l'))]) {
        $array[] = $date->format("D Y-m-d");
    }
}

Demo on 3v4l.org

Related