0

i have this code to find 3 consecutive dates in an array but i'm wondering if there is a better way to do this?

php code:

$datesarray = array('2012-10-01', '2012-10-03', '2012-10-04', '2012-10-05', '2012-10-08', '2012-10-09');

    $count = 0;
    $result = "Nothing found";

        foreach ($datesarray as $value) {
            if(strtotime($datesarray[$count]) - strtotime($datesarray[$count-1]) - strtotime($datesarray[$count-2]) == -1349150400) {
                $result = "3 Consecutive dates found";
            }
        $count++; 
        }  

    echo "Result: $result";
1
  • 1
    Wrong forum. Should be in code review instead. Commented May 7, 2014 at 18:01

1 Answer 1

1

Your script gives me:

Result: Nothing found

but there are 3 consecutive dates

I've changed the script:

<?php

$datesarray = array('2012-10-01', '2012-10-03', '2012-10-04', '2012-10-05', '2012-10-08', '2012-10-09');

$result = "Nothing found";


$diff = strtotime('2014-05-07') - strtotime('2014-05-06');

for ($i=2, $c=count($datesarray); $i<$c; ++$i) {
    if (strtotime($datesarray[$i-1]) - strtotime($datesarray[$i-2]) == $diff &&
        strtotime($datesarray[$i]) - strtotime($datesarray[$i-2]) == $diff * 2) {
            $result = "3 Consecutive dates found";                
            break;
    }

}
echo "Result: $result";  

and the result is

Result: 3 Consecutive dates found

Is this what you expected?

Sign up to request clarification or add additional context in comments.

2 Comments

mine shows Result: 3 Consecutive dates found... not sure why you got Nothing found with my code....
I have also warning in your script because in your foreach you check also not existing elements. On my PC in your script I have values 1349042400, 172800, -1348956000, -1349128800, -1349042400, -1349301600 in comparison

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.