PHP

Extracting and Indexing Data with PHP's `array_column`

Efficiently extract a specific column from a multi-dimensional array and use another column's values as keys for a new associative array in PHP.

<?php
$records = [
    ['id' => 101, 'name' => 'Apple', 'category' => 'Fruit', 'price' => 1.50],
    ['id' => 102, 'name' => 'Banana', 'category' => 'Fruit', 'price' => 0.75],
    ['id' => 103, 'name' => 'Carrot', 'category' => 'Vegetable', 'price' => 0.90],
    ['id' => 104, 'name' => 'Dates', 'category' => 'Fruit', 'price' => 2.20],
];

// Extract 'name' column
$names = array_column($records, 'name');
echo "Names:
";
print_r($names);

// Extract 'price' column and use 'id' as keys
$pricesById = array_column($records, 'price', 'id');
echo "
Prices by ID:
";
print_r($pricesById);

// Output:
// Names:
// Array
// (
//     [0] => Apple
//     [1] => Banana
//     [2] => Carrot
//     [3] => Dates
// )
//
// Prices by ID:
// Array
// (
//     [101] => 1.5
//     [102] => 0.75
//     [103] => 0.9
//     [104] => 2.2
// )
?>
How it works: `array_column()` is an extremely powerful function for working with multi-dimensional arrays (like results from a database query). It allows you to extract all values for a single key from an array of arrays. Optionally, you can provide a third argument to specify a key to be used as the index (key) for the returned array, transforming a list of records into an associative map indexed by a unique identifier. This simplifies data access and organization significantly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs