448191 Posted October 5, 2008 Share Posted October 5, 2008 Should be simple but I can't figure it out. Say I have an array like so: $pages = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); or any other array with sequential values that starts with 0 (or 1, doesn't matter). How do I assert that all values are indeed sequential, without looping through the values? Link to comment https://forums.phpfreaks.com/topic/127119-solved-checking-if-all-values-are-sequential-starting-from-1-or-0/ Share on other sites More sharing options...
AndyB Posted October 5, 2008 Share Posted October 5, 2008 If the array values are an arithmetic progression, then from count() and diff between consecutives you can determine the expected sum of all values. If it equals array_sum() then you have all values in the array. Link to comment https://forums.phpfreaks.com/topic/127119-solved-checking-if-all-values-are-sequential-starting-from-1-or-0/#findComment-657536 Share on other sites More sharing options...
448191 Posted October 5, 2008 Author Share Posted October 5, 2008 I figured as much, but didn't know how to calculate what the sum should be. I figured it out though: <?php $pages = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); var_dump( array_sum($pages) == (max($pages) + min($pages)) * (max($pages) / 2) ); Link to comment https://forums.phpfreaks.com/topic/127119-solved-checking-if-all-values-are-sequential-starting-from-1-or-0/#findComment-657564 Share on other sites More sharing options...
AndyB Posted October 5, 2008 Share Posted October 5, 2008 FYI - http://library.thinkquest.org/20991/gather/formula/data/213.html works for all arithmetic progressions. Link to comment https://forums.phpfreaks.com/topic/127119-solved-checking-if-all-values-are-sequential-starting-from-1-or-0/#findComment-657565 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.