Created
April 8, 2014 18:31
-
-
Save cyk/10167916 to your computer and use it in GitHub Desktop.
chunk_by_element_length.php
This file contains hidden or 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 | |
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
css-social-buttons