PHP

Extract Specific Column Values from an Array

Learn to easily extract a single column or property's values from a PHP array of associative arrays or objects using `array_column`.

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

// Get an array of all user names
$names = array_column($users, 'name');
print_r($names);

// Get an array of emails, indexed by user ID
$emailsById = array_column($users, 'email', 'id');
print_r($emailsById);

// Example with objects (same principle)
class User {
    public $id;
    public $name;
    public $email;
    public function __construct($id, $name, $email) {
        $this->id = $id; $this->name = $name; $this->email = $email;
    }
}
$userObjects = [
    new User(10, 'Eve', '[email protected]'),
    new User(11, 'Frank', '[email protected]'),
];

$objectNames = array_column($userObjects, 'name');
print_r($objectNames);
?>
How it works: The `array_column()` function provides a concise way to extract a single column from an array of associative arrays or objects. The first argument is the input array, the second is the column/property name to return, and the optional third argument specifies a column to use as the keys for the output array. This is extremely useful for generating simple lists or lookup maps from complex data structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs