Skip to content
troydavisson edited this page Nov 10, 2012 · 1 revision

Purpose

create_batch_list() allows you to pass a simple array of values and get back an array of values in batch format.

Example

<?php
$master_list = array(1,2,3,4,5,6,7,8,9,10);

$batches = create_batch_list($master_list, 3); // override the default and only get 3 per batch

$batch_count = 0;
foreach ($batches as $batch) {
        $batch_count++;
        echo "Batch #{$batch_count}: {$batch}\n";
}

//   Batch #1: 1,2,3
//   Batch #2: 4,5,6
//   Batch #3: 7,8,9
//   Batch #4: 10

The Code

<?php
function create_batch_list($batch_array, $num_per_batch = 10) {

        $return_array = array();

        if (is_array($batch_array)) {
                $this_count = 0;
                $this_item = "";

                foreach ($batch_array as $item) {
                        $this_count++;
                        $this_item .= "{$item},";

                        if ($this_count == $num_per_batch) {
                                $this_count = 0;
                                $return_array[] = preg_replace('/\,$/', '', $this_item);
                                $this_item = "";
                        }
                }
                if (!empty($this_item)) {
                        $return_array[] = preg_replace('/\,$/', '', $this_item);
                }
        }

        return $return_array;
}