PHP

Extracting a Column from an Array of Arrays

Learn to quickly extract values from a specific column across all rows in an array of associative arrays, producing a simple indexed array in PHP.

$users = [
    ['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($users, 'name');
// $names will be: ['Alice', 'Bob', 'Charlie']

// Extract 'name' values, using 'id' as keys
$namesById = array_column($users, 'name', 'id');
// $namesById will be: [101 => 'Alice', 102 => 'Bob', 103 => 'Charlie']
How it works: This snippet shows the powerful `array_column` function, which extracts a single column from a multi-dimensional array or an array of objects. It can return an indexed array of the column's values or an associative array using another specified column's values as keys, simplifying data manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs