note 94138 modified in function.array-slice by danbrown

From: Date: Mon, 19 Oct 2009 22:05:12 +0000
Subject: note 94138 modified in function.array-slice by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161886@lists.php.net to get a copy of this message
A flexible array_split function: <?php // split the given array into n number of pieces function array_split($array, $pieces=2) { if ($pieces < 2) return array($array); $newCount = ceil(count($array)/$pieces); $a = array_slice($array, 0, $newCount); $b = array_split(array_slice($array, $newCount), $pieces-1); return array_merge(array($a),$b); } // Examples: $a = array(1,2,3,4,5,6,7,8,9,10); array_split($a, 2); // array(array(1,2,3,4,5), array(6,7,8,9,10)) array_split($a, 3); // array(array(1,2,3,4), array(5,6,7), array(8,9,10)) array_split($a, 4); // array(array(1,2,3), array(4,5,6), array(7,8), array(9,10)) ?> --was-- A flexible array_split function: <? // split the given array into n number of pieces function array_split($array, $pieces=2) { if ($pieces < 2) return array($array); $newCount = ceil(count($array)/$pieces); $a = array_slice($array, 0, $newCount); $b = array_split(array_slice($array, $newCount), $pieces-1); return array_merge(array($a),$b); } // Examples: $a = array(1,2,3,4,5,6,7,8,9,10); array_split($a, 2); // array(array(1,2,3,4,5), array(6,7,8,9,10)) array_split($a, 3); // array(array(1,2,3,4), array(5,6,7), array(8,9,10)) array_split($a, 4); // array(array(1,2,3), array(4,5,6), array(7,8), array(9,10)) ?> http://php.net/manual/en/function.array-slice.php

« previous php.notes (#161886) next »