PHP

Extract a Column of Values from an Array

Learn to quickly extract values from a specific column (key) across an array of associative arrays or objects using PHP's `array_column` function.

$products = [
    ['id' => 101, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 102, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 103, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
    ['id' => 104, 'name' => 'Mouse', 'category' => 'Accessories', 'price' => 25],
];

// Extract all product names
$productNames = array_column($products, 'name');
print_r($productNames);

echo "
";

// Extract product IDs, using 'name' as the key for the new array
$productIdsByName = array_column($products, 'id', 'name');
print_r($productIdsByName);

echo "
";

// Working with objects (PHP 7.0+)
class Product {
    public $id;
    public $name;
    public $category;
    public function __construct($id, $name, $category) {
        $this->id = $id;
        $this->name = $name;
        $this->category = $category;
    }
}

$productObjects = [
    new Product(201, 'Desk', 'Furniture'),
    new Product(202, 'Chair', 'Furniture'),
    new Product(203, 'Lamp', 'Home Decor'),
];

$objectProductNames = array_column($productObjects, 'name');
print_r($objectProductNames);
How it works: The `array_column` function is an extremely useful and efficient PHP function for extracting a single column (or property for objects) from a multi-dimensional array or an array of objects. It can return the values directly, or it can use another column's values as keys for the resulting array. This is particularly handy when you need to quickly get a list of IDs, names, or any other specific attribute from a collection of records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs