← Back to all snippets
PHP

Extract Specific Column from PHP Array of Associative Arrays

Use array_column in PHP to quickly extract all values for a single key from a list of associative arrays, creating a new indexed array.

<?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' => 'Doe']
];

// Get all 'first_name' values
$firstNames = array_column($records, 'first_name');
print_r($firstNames);

// Get 'id' values, indexed by 'first_name'
$idsByFirstName = array_column($records, 'id', 'first_name');
print_r($idsByFirstName);
?>
How it works: The `array_column()` function provides a concise way to extract a specific column (key) from a multi-dimensional array or an array of objects. It can also be used to index the resulting array by another column's values, making it very versatile for data manipulation like quickly getting a list of names or creating a lookup map.

Need help integrating this into your project?

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

Hire DigitalCodeLabs