[php-src] Issue #14582: array_partition function

From: Date: Sun, 16 Jun 2024 08:51:41 +0000
Subject: [php-src] Issue #14582: array_partition function
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-247096@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/14582 Author: remco-pc ### Description this function is like array_chunk, but instead of making it chunk size, it will use partition. The difference with array_chunk is that it chunks the elements in a multidimensional array up to size. ```php function array_partition($array=[], $size=1, $preserve_keys=false): array { $array = (array) $array; $size = (int) $size; if($size < 1){ throw new Exception('Size must be greater than 0'); } $result = []; $partition = []; $nr = 0; $counter = 0; $count = count($array); $amount = (int) ceil($count / $size); if($preserve_keys === false){ foreach ($array as $value) { $partition[] = $value; $counter++; if ($counter === $amount) { $result[] = $partition; $partition = []; $counter = 0; } } } else { foreach ($array as $key => $value) { $partition[$key] = $value; $counter++; if ($counter === $amount) { $result[] = $partition; $partition = []; $counter = 0; } } } if(!empty($partition)){ $result[] = $partition; } return $result; } ``` ```php $partition = array_partition($array, 2); ``` results in ```php $partition = [ 0 => [...], 1 => [...] ]

« previous php.bugs (#247096) next »