PHP

Extract a Specific Column from an Array of Objects/Arrays

Discover how to quickly extract values from a specific column or key from an array of associative arrays or objects using `array_column` in PHP, perfect for list generation.

<?php

$records = [
    ['id' => 101, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 102, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 103, 'name' => 'Charlie', 'email' => '[email protected]']
];

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

// Extract 'email' values, using 'id' as the keys for the new array
$emailsById = array_column($records, 'email', 'id');
print_r($emailsById);

// Output for $names:
// Array
// (
//     [0] => Alice
//     [1] => Bob
//     [2] => Charlie
// )

// Output for $emailsById:
// Array
// (
//     [101] => [email protected]
//     [102] => [email protected]
//     [103] => [email protected]
// )

?>
How it works: `array_column()` is an incredibly efficient function for extracting a single column (all values associated with a specific key) from an array of associative arrays or objects. It can optionally use another column's values as the keys for the new array, which is very handy for creating lookup tables. This function simplifies data transformation for tasks like populating dropdowns or creating indices.

Need help integrating this into your project?

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

Hire DigitalCodeLabs