2

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.

Nick
  • 138,499
  • 22
  • 57
  • 95
fynn1307
  • 71
  • 6

1 Answers1

4

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thaniks for your answer. In my case, in mysql for is for each day a coloumn. if column monday = 1 display monday; if tueday = 0 hide tuesday. Can you please help me to solve this problem – fynn1307 Dec 21 '20 at 06:12
  • So inside `$row` you have values e.g. `$row['monday'] = 1, $row['tuesday'] = 0, ...` etc.? – Nick Dec 21 '20 at 06:13
  • Yes, you are right :) – fynn1307 Dec 21 '20 at 06:14
  • @fynn1307 please see my edit; that should do what you want – Nick Dec 21 '20 at 06:18
  • Thank you very much for your help! It worked, I have marked your question, is this all I could do for you??? – fynn1307 Dec 21 '20 at 06:20
  • @fynn1307 I'm glad to hear it. At your current level of rep, accepting the answer is all you can do (and is plenty). Once you reach 15 rep, you can upvote answers as well as accept them. – Nick Dec 21 '20 at 06:21