Skip to content

Instantly share code, notes, and snippets.

@cyk
Created April 8, 2014 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyk/10167916 to your computer and use it in GitHub Desktop.
Save cyk/10167916 to your computer and use it in GitHub Desktop.
chunk_by_element_length.php
<?php
/**
* Chunk by (combined) Element Length
*
* Similar to PHP's array_chunk but chunks on combined element length instead of element count.
* Takes an input array of elements and chunks by combined string lengths.
*
* NOTE: Any values that exceed chunk length will be excluded.
*
* @access public
* @param array $input the input array
* @param int $chunklen string length to chunk array by
* @return array chunked array
*/
public static function chunk_by_element_length(array $input, $chunklen)
{
$output = array();
while ($input)
{
$length_remaining = $chunklen;
$chunk = array();
while ($input && $length_remaining)
{
$value_length = strlen(reset($input));
if ($value_length > $chunklen)
{
array_shift($input);
}
else if ($value_length <= $length_remaining)
{
$chunk[] = array_shift($input);
$length_remaining -= $value_length;
}
else
{
break;
}
}
$output[] = $chunk;
}
return $output;
}
Copy link

ghost commented Apr 8, 2014

css-social-buttons

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment