PHP

Extract Specific Column from PHP Array of Arrays

Utilize array_column() to efficiently extract all values for a specific key from an array of associative arrays, generating a simple list of those values.

<?php

$records = [
    ['id' => 101, 'name' => 'Product A', 'price' => 150],
    ['id' => 102, 'name' => 'Product B', 'price' => 200],
    ['id' => 103, 'name' => 'Product C', 'price' => 120],
    ['id' => 104, 'name' => 'Product D', 'price' => 300],
];

// Extract all 'name' values
$productNames = array_column($records, 'name');

echo "Product Names:
";
print_r($productNames);

// Extract 'price' values, indexed by 'id'
$productPricesById = array_column($records, 'price', 'id');

echo "
Product Prices (indexed by ID):
";
print_r($productPricesById);

?>
How it works: The array_column() function is demonstrated here for extracting a specific column from a multi-dimensional array (or an array of objects). It can pull out all values associated with a given key, creating a new indexed array. Optionally, a third argument can be provided to specify a key whose values should be used as the keys for the output array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs