PHP

Extract a Single Column from an Array of Associative Arrays

Use `array_column` to efficiently extract a specific column's values or create new associative arrays with custom keys from a list of records in PHP.

<?php
$users = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
];

// Extract just the 'name' column
$names = array_column($users, 'name');
// $names will be ['Alice', 'Bob', 'Charlie']
print_r($names);

// Extract 'name' column and use 'id' as keys
$namesWithIds = array_column($users, 'name', 'id');
// $namesWithIds will be [1 => 'Alice', 2 => 'Bob', 3 => 'Charlie']
print_r($namesWithIds);
?>
How it works: The `array_column` function is a powerful tool for working with arrays of associative arrays or objects. It allows you to extract all values for a single key from a multi-dimensional array, optionally using another key's values as the keys for the new array. This is highly useful for generating lists of specific data points or reindexing data based on unique identifiers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs