Skip to content
← Back to Functions
Code

Batch Chunk Planner

Splits large processing jobs into safe chunk ranges with progress metadata.

Function signature

ogPlanBatchChunks(total_rows, chunk_size = 1000, resume_offset = 0)

Categories

  • Performance

Parameters

total_rowsTotal records to process.chunk_sizeNumber of records in each chunk.resume_offsetZero-based offset where processing should resume.

Return value

Short public-safe status message.

  • chunks
  • chunk_count
  • total_rows
  • resume_offset

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Splits large processing jobs into safe chunk ranges with progress metadata.
 *
 * Primary use case: Imports, exports, email jobs, migrations.
 * Typical inputs: total rows, chunk size, resume state.
 * Typical output: chunk plan array.
 *
 * Implementation note: Persist progress for resumable jobs.
 *
 * @param int $total_rows Total records to process.
 * @param int $chunk_size Number of records in each chunk.
 * @param int $resume_offset Zero-based offset where processing should resume.
 * @return array Structured chunk plan.
 */
function ogPlanBatchChunks($total_rows, $chunk_size = 1000, $resume_offset = 0) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	$total_rows = (int)$total_rows;
	$chunk_size = (int)$chunk_size;
	$resume_offset = (int)$resume_offset;

	if ($total_rows < 0) {
		$result['message'] = 'Total rows cannot be negative.';
		return $result;
	}

	if ($chunk_size < 1) {
		$chunk_size = 1000;
	}

	if ($chunk_size > 10000) {
		$chunk_size = 10000;
	}

	if ($resume_offset < 0) {
		$resume_offset = 0;
	}

	if ($resume_offset > $total_rows) {
		$resume_offset = $total_rows;
	}

	$chunks = array();
	$current_offset = $resume_offset;
	while ($current_offset < $total_rows) {
		$limit = $chunk_size;
		if (($current_offset + $limit) > $total_rows) {
			$limit = $total_rows - $current_offset;
		}

		$chunks[] = array(
			'offset' => $current_offset,
			'limit' => $limit,
			'start_row' => $current_offset + 1,
			'end_row' => $current_offset + $limit
		);

		$current_offset += $limit;
	}

	$result['success'] = true;
	$result['message'] = 'Batch chunks planned.';
	$result['data'] = array(
		'total_rows' => $total_rows,
		'chunk_size' => $chunk_size,
		'resume_offset' => $resume_offset,
		'chunk_count' => count($chunks),
		'chunks' => $chunks
	);

	return $result;
}