← Back to Chapters

PHP Array Column & Chunk Functions

? PHP Array Column & Chunk Functions

? Quick Overview

PHP provides powerful built-in array functions that simplify working with data collections. The array_column() function helps extract values from a specific column of a multidimensional array, while array_chunk() splits a large array into smaller arrays of fixed size. These functions are especially useful in real-world scenarios such as database results processing, pagination, and data transformation.

? Key Concepts

  • array_column() extracts values from a single column in a multidimensional array.
  • array_chunk() divides an array into smaller chunks of a given size.
  • Both functions return new arrays without modifying the original data.

? Syntax & Theory

  • array_column(array $array, mixed $column_key)
  • array_chunk(array $array, int $length)

? Code Example: array_column()

? View Code Example
// Extract the 'name' column from a multidimensional array
<?php
$people = array(
array("id" => 1, "name" => "John", "age" => 25),
array("id" => 2, "name" => "Jane", "age" => 30),
array("id" => 3, "name" => "Bob", "age" => 35)
);
$names = array_column($people, "name");
print_r($names);
?>

? Explanation

The function extracts all values associated with the key name from each sub-array, returning a simple indexed array of names.

? Code Example: array_chunk()

? View Code Example
// Split an array into chunks of size 3
<?php
$numbers = array(1,2,3,4,5,6,7,8,9);
$chunks = array_chunk($numbers, 3);
print_r($chunks);
?>

? Explanation

The array is divided into three smaller arrays, each containing three elements. This is commonly used for pagination or batch processing.

? Interactive Visualization

? Visual Chunk Representation
// Conceptual visualization of array chunks
[1,2,3] | [4,5,6] | [7,8,9]

? Use Cases

  • Extracting column values from database query results.
  • Paginating records into fixed-size pages.
  • Processing large datasets in batches.

✅ Tips & Best Practices

  • Always verify the column key exists before using array_column().
  • Use array_chunk() for memory-efficient batch operations.
  • Combine these functions with loops for advanced data processing.

? Try It Yourself

  • Create a student array and extract names using array_column().
  • Divide an array of 20 numbers into chunks of 5.
  • Calculate the average of values extracted with array_column().