PHP

Extracting a Specific Column from Array of Arrays

Quickly extract values of a specific column from a multi-dimensional PHP array into a new one-dimensional array using `array_column`.

<?php
$records = [
    ['id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'],
    ['id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith'],
    ['id' => 3, 'first_name' => 'Peter', 'last_name' => 'Jones'],
    ['id' => 4, 'first_name' => 'John', 'last_name' => 'Doe'], // Duplicate first name
];

// Get a list of all first names
$firstNames = array_column($records, 'first_name');
print_r($firstNames);

// Get IDs indexed by first names (if unique, otherwise last one wins)
$indexedByFirstName = array_column($records, 'id', 'first_name');
print_r($indexedByFirstName);

// Get full names by combining first and last names (requires array_map first)
$fullNames = array_map(function($record) {
    return $record['first_name'] . ' ' . $record['last_name'];
}, $records);
print_r($fullNames); // This shows array_column cannot directly combine columns, use array_map for that.

// More direct example using array_column for a simple list of values
$data = [
    ['product' => 'Laptop', 'price' => 1200],
    ['product' => 'Keyboard', 'price' => 75],
    ['product' => 'Mouse', 'price' => 25],
];
$prices = array_column($data, 'price');
print_r($prices);
?>
How it works: `array_column()` is a highly efficient function for extracting all values from a single column in a multi-dimensional array or an array of objects. It can optionally also be used to index the resulting array by the values of another column. This simplifies data manipulation, such as getting a list of specific attributes or preparing data for lookup tables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs