0

I have this Array:

Array
(
    [0] => 2012-08-21
    [1] => 2012-08-22
    [2] => 2012-08-23
    [3] => 2012-08-24
    [4] => 2012-08-25
    [5] => 2012-08-26
    [6] => 2012-08-27
    [7] => 2012-08-28
    [8] => 2012-08-29
    [9] => 2012-08-30
)

To create this array I'm using this:

function getAllDatesBetweenTwoDates($strDateFrom,$strDateTo)
{
    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400; // add 24 hours
            array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    }
    return $aryRange;
}

$fromDate = '2012-08-21';
$toDate = '2012-08-30';

$dateArray = getAllDatesBetweenTwoDates($fromDate, $toDate);


for($i=0, $count = count($dateArray);$i<$count;$i++) {
 echo $dateArray[$i] . " - " . $dateArray[$i++] . "<br>";
}

But this skips the second date and just shows the same date next to each other, but I'm eventually wanting to put these arrays in a query to get data between each of the two dates.

This currently returns:

2012-08-21 - 2012-08-21
2012-08-23 - 2012-08-23
2012-08-25 - 2012-08-25
2012-08-27 - 2012-08-27
2012-08-29 - 2012-08-29

But I want it to return:

2012-08-21 - 2012-08-22
2012-08-22 - 2012-08-23
2012-08-23 - 2012-08-24
2012-08-24 - 2012-08-25
2012-08-25 - 2012-08-26
2012-08-26 - 2012-08-27
2012-08-27 - 2012-08-28
2012-08-28 - 2012-08-29
2012-08-29 - 2012-08-30
2012-08-30 - 2012-08-30

How can I achieve this?

2 Answers 2

2

You increment i twice, and this is the problem. You have to use $i+1 instead of i++ inside for iteration:

for($i=0, $count = count($dateArray);$i<$count;$i++) {
 echo $dateArray[$i] . " - " . $dateArray[$i+1] . "<br>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is not in the function itself, it's in the way you print it (double increment). Try this loop:

for($i=0; $i<count($dateArray)-1;$i++) {
   echo $dateArray[$i] . " - " . $dateArray[$i+1] . "<br>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.