PHP

Extract a Single Column from an Array of Arrays/Objects in PHP

Discover how to quickly extract a specific column's values from a multi-dimensional PHP array or an array of 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]'],
    ['id' => 4, 'name' => 'David', 'email' => '[email protected]'],
];

// Extracting all 'name' values
$names = array_column($users, 'name');
/*
Expected output for $names:
[
    "Alice",
    "Bob",
    "Charlie",
    "David",
]
*/
echo "Names: 
";
print_r($names);

// Extracting 'email' values, using 'id' as keys
$emailsById = array_column($users, 'email', 'id');
/*
Expected output for $emailsById:
[
    1 => "[email protected]",
    2 => "[email protected]",
    3 => "[email protected]",
    4 => "[email protected]",
]
*/
echo "
Emails by ID: 
";
print_r($emailsById);

// Example with objects (can also use array_column with objects)
class Product {
    public $id;
    public $title;
    public $price;
    public function __construct($id, $title, $price) {
        $this->id = $id;
        $this->title = $title;
        $this->price = $price;
    }
}

$products = [
    new Product(101, 'Book A', 29.99),
    new Product(102, 'Book B', 15.50),
    new Product(103, 'Book C', 45.00),
];

// Extracting product titles
$productTitles = array_column($products, 'title');
/*
Expected output for $productTitles:
[
    "Book A",
    "Book B",
    "Book C",
]
*/
echo "
Product Titles: 
";
print_r($productTitles);
?>
How it works: The `array_column()` function is a highly efficient built-in PHP function designed to extract values from a single column (or property for objects) from a multi-dimensional array or an array of objects. It can optionally take a third argument to specify a column whose values should be used as the keys for the output array. This is incredibly useful for quickly transforming complex data structures into simpler lists or lookup tables, such as getting a list of all user names or mapping user IDs to their emails.

Need help integrating this into your project?

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

Hire DigitalCodeLabs