Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Created May 25, 2017 03:01
Show Gist options
  • Save shadowhand/9b402c62f520c7219c30566422f93bd5 to your computer and use it in GitHub Desktop.
Save shadowhand/9b402c62f520c7219c30566422f93bd5 to your computer and use it in GitHub Desktop.
Array chunking for SplFixedArray
<?php
// Copyright (c) 2017 Woody Gilk (@shadowhand)
// MIT License
/**
* A chunking function for SplFixedArray
*
* Operates the same as array_chunk() but without $preserve_keys, for obvious reasons.
*
* @param SplFixedArray $arr
* @param int $size
*
* @return SplFixedArray[]
*/
function array_chunk_fixed(SplFixedArray $arr, $size) {
// Determine the number of chunks that need to be created
$chunks = new SplFixedArray(ceil(count($arr) / $size));
foreach ($arr as $idx => $value) {
if ($idx % $size === 0) {
// Create a new chunk every time we reach the maximum size
$chunks[$idx / $size] = $chunk = new SplFixedArray($size);
}
// Add to the current chunk
$chunk[$idx % $size] = $value;
}
// Reduce the size of the final chunk to match remainder
$chunk->setSize(count($arr) % $size);
return $chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment