Created
May 25, 2017 03:01
-
-
Save shadowhand/9b402c62f520c7219c30566422f93bd5 to your computer and use it in GitHub Desktop.
Array chunking for SplFixedArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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