PHP

Extracting Column Values from an Array of Arrays in PHP

Discover how to efficiently retrieve all values from a specific column within a multi-dimensional PHP array using `array_column`. Ideal for creating lists or dropdown options quickly.

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

// Get an array containing only the 'first_name' values
$firstNames = array_column($records, 'first_name');
print_r($firstNames);

// Get 'first_name' values, using 'id' as the keys of the new array
$namesById = array_column($records, 'first_name', 'id');
print_r($namesById);
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's particularly useful for working with database query results or other arrays of associative arrays. You can optionally specify a `key_column` to use the values of that column as the keys in the resulting array, making data access more intuitive.

Need help integrating this into your project?

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

Hire DigitalCodeLabs