Jump to content

[SOLVED] Checking if all values are sequential, starting from 1 (or 0)


448191

Recommended Posts

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?

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.

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)
);

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.