Try to check if a day is inserted between two dates

Asked

Viewed 33 times

0

Good, I have a function that keeps me in an array the days between two dates. Next, I want to check if a given day belongs to the interval and create a foreach that goes through the array with all the dates and, in case the date is inserted, it gives an echo of '1'.

The point is that it never returns me 1 even when the date corresponds to an array value.

My code is this::

$data_inicial = new DateTime(implode('-', array_reverse(explode('/', '10/05/2010'))));
$data_final = new DateTime(implode('-', array_reverse(explode('/', '07/06/2010'))));

while ($data_inicial <= $data_final) {
    $datasint[] = $data_inicial->format('d/m/Y') . '<br />' . PHP_EOL;
    $data_inicial->add(DateInterval::createFromDateString('1 days'));
}


foreach ($datasint as $key => $value) {
    if ($value == '25/05/2010') {
        echo '1';
    }
}

Can anyone figure out where the bug is? If you want to copy the code and try it yourself!

  • 1

    You are concatenating <br /> on the dates, then within the foreach the values are 10/05/2010<br />, 11/05/2010<br />, 25/05/2010<br /> etc..

  • thank you very much!

  • If it’s just to check, you don’t need to create an array with every day, just check if the date in question is longer than the initial date and shorter than the final date.

1 answer

0


Like the hkotsubo said, you are concatenating <br /> in each array value. And when performing the comparison with the string it happens as follows:

foreach ($datasint as $key => $value) {
    if ('25/05/2010<br />' == '25/05/2010') {
        echo '1';
    }
}

Just remove the concatenation.

while( $data_inicial <= $data_final ) {
    $datasint[]= $data_inicial->format( 'd/m/Y' );
    $data_inicial->add(DateInterval::createFromDateString( '1 days' ));
}

Merits of the response to hkotsubo, I answered here to facilitate in the search for the answer.

Browser other questions tagged

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