Rildo Gomez
Rildo Gomez

Reputation: 305

How to differentiate days between a list of dates? PHP

I've been trying to make a list of days of when I went to school and when I didn't.

I'm looping the days here. Another array contains the days I didn't go to school.

<?php
$fecha1 = "2015-03-10";
$fecha2 = date("Y-m-d",strtotime($fecha1."+ 10 days"));
$fecha3 = array("2015-03-11","2015-03-14","2015-03-17");
$j=1;

for($i=$fecha1;$i<$fecha2;$i = date("Y-m-d", strtotime($i ."+ 1 days"))){
    for ($n=0; $n <count($fecha3) ; $n++) { 
        if($i==$fecha3[$n]){
            $obs="not there";

        }else{
            $obs="there";       
        }
    }   
    echo "Day ".$j." ".$i."---".$obs."<br />";
    $j++;
}
?>

and the output is

Day 1 2015-03-10---there
Day 2 2015-03-11---there
Day 3 2015-03-12---there
Day 4 2015-03-13---there
Day 5 2015-03-14---there
Day 6 2015-03-15---there
Day 7 2015-03-16---there
Day 8 2015-03-17---not there
Day 9 2015-03-18---there
Day 10 2015-03-19---there

I dont understand why it doesnt say "not there" on day 2 2015-03-11 and day 5 2015-03-14, someone help me please I've been with this for hours.

Upvotes: 3

Views: 95

Answers (2)

redelschaap
redelschaap

Reputation: 2814

It's because 2015-03-11 and 2015-03-14 are the first two values in the $fecha3 array, and $obs gets overwritten in that second for loop.

In this case I would recommend using in_array() instead of a second for loop:

$fecha1 = '2015-03-10';
$fecha2 = 10;
$fecha3 = array('2015-03-11', '2015-03-14', '2015-03-17');

for ($i = 0; $i < $fecha2; $i++) {
    $date = date('Y-m-d', strtotime($fecha1 . ' + ' . $i . ' days'));
    $obs = in_array($date, $fecha3) ? 'not there' : 'there';
    echo 'Day ' . ($i + 1) . ' ' . $date . '---' . $obs . '<br />';
}

Upvotes: 1

Kevin
Kevin

Reputation: 41885

You should add a break once the needle is found:

if($i==$fecha3[$n]){
        $obs="not there";
        break; // this is important
    }else{
        $obs="there";
    }

Another alternative is also in_array() for searching:

if(in_array($i, $fecha3)){
    $obs="not there";
}else{
    $obs="there";
}

Upvotes: 3

Related Questions