Display first and last element on foreach

I have this little part:

foreach($events as $key=>$event){   
    if($event->order ==  $orderss){

        $id = $event->id;
        $date = new DateTime($event->start);
        $start = $date->format('H:i Y-m-d ');
        $date_end = new DateTime($event->end);
        $end = $date_end->format('H:i Y-m-d ');
        echo $start.' - '.$end.'<br>';

    }       
}

And it's returning the next values:

18:00 2015-04-29 - 19:00 2015-04-29 

19:00 2015-04-29 - 20:00 2015-04-29 

20:00 2015-04-29 - 21:00 2015-04-29 

21:00 2015-04-29 - 22:00 2015-04-29 

AND

11:00 2015-05-11 - 12:00 2015-05-11

12:00 2015-05-11 - 13:00 2015-05-11 

13:00 2015-05-11 - 14:00 2015-05-11

My question is if I can tak over the foreach the value 18:00 2015-04-29 AND 22:00 2015-04-29

11:00 2015-05-11 AND 14:00 2015-05-11 ?

This goes inside a table column, on foreach creates a new column with those dates, if I use $key==0, then only the first column fills up and the rest, stays empty

Answers


Use the $key. Assuming $event is an array with an index from 0 to count($event)-1:

foreach($events as $key=>$event){   
    if($event->order ==  $orderss && (($key == 0) || ($key == count($event)-1))){
        $id = $event->id;
        $date = new DateTime($event->start);
        $start = $date->format('H:i Y-m-d ');
        $date_end = new DateTime($event->end);
        $end = $date_end->format('H:i Y-m-d ');
        echo $start.' - '.$end.'<br>';
     }       
  }

If you simply want the first and last values of the array you could use array_shift and array_pop.

$start=new DateTime(array_shift( $events ));
$end=new DateTime(array_pop($events));

Use end($array); for the last element and for the first element reset($array);


//Get the last element
end($events); $last_key = key($events);
//Reset and get the first element
reset($events); $first_key = key($events);

//Now get the dates
$first_date = $events[$first_key];
$last_date = $events[$last_key];

echo $first_date . '<br />' . $last_date;

I get the last one first because I'm resetting the pointer afterwards anyway. This way you also get the keys which might come in handy later.


For first value -

$first = current($events);

For last value -

$last = end($events);

Need Your Help

SwingController get page coordinate

java swing icepdf

Using IcePdf (ver 1.8) i integrate a SwingController into my JPanel to use it in my application. Since the page displayed into the SwingController is in a specific position into the controller.

Debugger for debugging my OS

c debugging assembly error-handling operating-system

I want a debugger to debug my OS. At many places i am not being able to figure out what is wrong. So is there any debugger which can debug operating systems? can i do it with gdb?