Foreach - Conditions within a period

Asked

Viewed 42 times

0

Is it possible to place an if/Else condition inside a foreach? Below part of a code, where you enter the date range in the bank via $_POST. The question is: Is it possible to place an if/Else within this range? Ex: If it is Saturday, do not fill, or if it is Saturday fill in a certain time.

    $start = new DateTime($_POST["data1"]); 


    $end = new DateTime($_POST["data2"]); 


   $interval = new DateInterval("P1D"); 



    $period = new DatePeriod($start, $interval, $end);



   foreach($period as $p)
   {
    $x =$p->format('Y-m-d');


    $sql ="INSERT INTO dt(data) VALUES('$x')";    

         $x = $connection->prepare($sql);

    if($x->execute())
  • Your problem was not very clear. Could give details?

  • Sure! I’m taking a date range and entering it into the bank as the code shows. I do this by means of a foreach that will catch this interval of datePeriod. I would like to put conditions within the capture of this date range. For example, if in this interval one day of the week falls as Saturday jumps, it does not record.Just an example

1 answer

1


Yes, the foreach is just a repeat loop, meaning we will repeat a block of instructions any. In this case, for each $periodo element there will be a loop of repetition. An example of a condition within the foreach, similar to the example you gave would be:

foreach($period as $p){
    $x =$p->format('Y-m-d');
    if(date('N', strtotime($p))== 6){ // // date('N', strtotime($p)) retorna um numero entre 0 (domingo) e 6 (sábado)
         $sql ="INSERT INTO dt(data) VALUES('$x')";    
         $x = $connection->prepare($sql);
         if($x->execute())
    }
}
  • Thanks Dude! I tried to run as you showed but the error "Notice: Undefined Property: Dateperiod::$dayofweek" appeared

  • I was wrong, I thought $periodo was a Carbon object. I’m going to edit the answer by following this example code: https://3v4l.org/dJ9q7

  • Perfect guy! Saved me vlw brother worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.