Pagination + Shuffle

having about 500 pages in my collection, I found the shuffle algorithm above is showing some deficiency (pages in front of the collection are not getting as thoroughly shuffled as pages more towards the end of the collection, which is not ideal if the pages are pre-sorted by a field with only a small number of possible inputs. In my case – 500+ pages with one of ~10 different topics each – the first items in the returned collection would always belong to the same topic).

I replaced this shuffle loop:

for ($i = 0; $i < $size; ++$i) {
    list($chunk) = array_splice($keys, mt_rand(0, $size - 1), 1);
    array_push($keys, $chunk);
}

with this:

$order = array_map(function($val) {return mt_rand(); }, range(1, $size));
array_multisort($order, $keys);

and it seems to be working better.

3 Likes