PHP

Extract Specific Columns from PHP Arrays with `array_column`

Learn to quickly extract values from a single column in a multidimensional PHP array using `array_column`, optionally using another column for keys.

<?php

$records = [
    ['id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe'],
    ['id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith'],
    ['id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones'],
    ['id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Pan'],
];

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

// Get a list of IDs, using 'last_name' as keys
$idByLastName = array_column($records, 'id', 'last_name');
echo "
IDs keyed by Last Name:
";
print_r($idByLastName);

?>
How it works: The `array_column` function returns the values from a single column in the input array. It's incredibly efficient for extracting a specific field from an array of arrays or objects, creating a new one-dimensional array. Optionally, a third argument can be provided to specify which column should be used as the keys for the returned array, useful for creating lookup tables or quick data access.

Need help integrating this into your project?

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

Hire DigitalCodeLabs