PHP

Extract a Column from an Array of Arrays

Efficiently extract values from a specific column across multiple nested arrays in PHP using the array_column function, ideal for data processing.

<?php
$records = [
    [
        'id' => 101,
        'name' => 'Alice',
        'age' => 25
    ],
    [
        'id' => 102,
        'name' => 'Bob',
        'age' => 30
    ],
    [
        'id' => 103,
        'name' => 'Charlie',
        'age' => 35
    ]
];

// Extract just the 'name' column
$names = array_column($records, 'name');
print_r($names);

// Extract the 'id' column and use it as keys for the 'name' column
$names_by_id = array_column($records, 'name', 'id');
print_r($names_by_id);

// Extract a non-existent column (returns empty array)
$emails = array_column($records, 'email');
print_r($emails);
?>
How it works: The `array_column()` function is incredibly useful for extracting a single column from a multi-dimensional array or an array of objects. It takes the array, the key/property name for the column to retrieve, and optionally, a key to use as the index for the new array. This eliminates the need for manual loops to build new arrays from specific properties, streamlining data extraction tasks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs