note 130574 added to function.array-slice

From: Date: Sun, 14 Dec 2025 03:04:41 +0000
Subject: note 130574 added to function.array-slice
Groups: php.notes 
Request: Send a blank email to php-notes+get-222457@lists.php.net to get a copy of this message
another function of array_chunk, make N chunks divided in equal parts <?php function array_chunk_ep(array $array, int $num, $preserve_keys = false) { $ac = count($array); $asl = (int) ($ac / $num); $arexc = $ac - $asl * $num; $offset = 0; $result = []; for ($i = 0; $i < $num; $i++) { $length = $asl + ((0 < $arexc--) ? 1 : 0); $result[] = array_slice($array, $offset, $length, $preserve_keys); $offset += $length; } return $result; } print_r(array_chunk_ep(range(0, 23), 5)); /* Array ( [0] => Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ) [1] => Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 [4] => 9 ) [2] => Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 [4] => 14 ) [3] => Array ( [0] => 15 [1] => 16 [2] => 17 [3] => 18 [4] => 19 ) [4] => Array ( [0] => 20 [1] => 21 [2] => 22 [3] => 23 ) ) */ print_r(array_chunk_ep([1 => 'a', 3 => 'b', 5 => 'c', 7 => 'd',], 3, true)); /* Array ( [0] => Array ( [1] => a [3] => b ) [1] => Array ( [5] => c ) [2] => Array ( [7] => d ) ) */ ?> ---- Server IP: 206.189.2.9 Probable Submitter: 133.106.35.87 ---- Manual Page -- https://php.net/manual/en/function.array-slice.php Edit -- https://main.php.net/note/edit/130574 Del: integrated -- https://main.php.net/note/delete/130574/integrated Del: useless -- https://main.php.net/note/delete/130574/useless Del: bad code -- https://main.php.net/note/delete/130574/bad+code Del: spam -- https://main.php.net/note/delete/130574/spam Del: non-english -- https://main.php.net/note/delete/130574/non-english Del: in docs -- https://main.php.net/note/delete/130574/in+docs Del: other reasons-- https://main.php.net/note/delete/130574 Reject -- https://main.php.net/note/reject/130574 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222457) next »