Array listing with start and end

1

Example ..

$inicio = '11:00';
$fim = '13:00';
$array = ['10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30'];

I need to list the array .. but using the start value and final value .. excluding what is before $inicio .. and what is after $final .

asked by anonymous 07.08.2017 / 20:19

3 answers

3

Make a validation of the 2 values and populate an array.

$inicio = '12:00';
$fim = '13:00';
$array = ['10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30'];
$times = [];
foreach($array as $time){
    if( ($time >= $inicio && $time <=$fim ) ){
        array_push($times, $time);
    }
}
var_dump($times);
    
07.08.2017 / 21:03
1

You can use the array_filter function to do the calculation. In PHP, even if it is string it is possible to make the comparisons:

$horas = array_filter($array, function ($hora) use ($inicio, $fim) {
    return $hora >= $inicio && $hora <= $fim;
});

This function will create a new array based on the result of the boolean expression returned by the function. If true, the item is kept in array . If it is false, it is ignored.

It is important to note that keys are retained when you use array_filter . If you need to reorder array , you can call array_values to solve the problem:

$horas = array_filter($array, function ($hora) use ($inicio, $fim) {
    return $hora >= $inicio && $hora <= $fim;
});

$horas = array_values($horas);
    
07.08.2017 / 21:07
1

Just for the knowledge. If you are working with the full date and only the hours are important. You can easily resolve the issue using the DateTime .

$inicio = new DateTime('2017-08-07 11:00:00');
$fim = new DateTime('2017-08-07 13:00:00');

$array = [
    '2017-08-07 10:00:00',
    '2017-08-07 10:30:00',
    '2017-08-07 11:00:00',
    '2017-08-07 11:30:00',
    '2017-08-07 12:00:00',
    '2017-08-07 12:30:00',
    '2017-08-07 13:00:00',
    '2017-08-07 13:30:00'
];


$horas = [];
foreach($array as $hora) {
    $hora = new DateTime($hora);
    if ($hora >= $inicio && $hora <= $fim) {
       array_push($horas, $hora->format('H:i'));
    }
}

var_dump($horas);

//Saída
//array(5) {
//    [0]=>
//  string(5) "11:00"
//    [1]=>
//  string(5) "11:30"
//    [2]=>
//  string(5) "12:00"
//    [3]=>
//  string(5) "12:30"
//    [4]=>
//  string(5) "13:00"
//}
    
07.08.2017 / 21:28