← Back to all snippets
PHP

Extracting a Specific Column from an Array of Arrays

Learn how to easily extract a single column of values from a multi-dimensional array of associative arrays in PHP using the array_column() function, perfect for data transformation.

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

$userNames = array_column($users, 'name');
$userIds = array_column($users, 'id');

echo "User Names:
";
print_r($userNames);

echo "
User IDs:
";
print_r($userIds);

// With index key
$usersIndexedById = array_column($users, 'name', 'id');
echo "
User Names Indexed by ID:
";
print_r($usersIndexedById);
?>
How it works: The array_column() function extracts a single column from a multi-dimensional array or an array of objects. It's incredibly useful for transforming complex data structures into simpler lists for further processing, such as getting a list of all names or IDs. You can specify the column to extract by its key (e.g., 'name') and optionally provide a third argument to use another column's values as the keys for the new array, creating a powerful lookup structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs