PHP array_column() - Complete Guide with Examples
Mahesh Waghmare The array_column() function extracts a single column from a multi-dimensional array. It’s extremely useful for working with database results and structured data.
This guide covers everything about array_column(), from basic usage to advanced patterns.
Introduction to array_column()
array_column() extracts values from a specified column in a multi-dimensional array, similar to SQL’s SELECT column operation.
Key Characteristics:
- Extracts column values
- Can use index key
- Works with associative arrays
- Returns indexed array
Common Use Cases:
- Extract IDs from database results
- Get specific field from array of objects
- Transform data structures
- Create lookup arrays
Syntax and Parameters
Function Signature
array_column(array $array, string|int|null $column_key, string|int|null $index_key = null): array
Parameters
$array: Multi-dimensional array
$column_key: Column to extract
$index_key: Optional key for result array
Basic Usage Examples
Extract Column
$users = [
['id' => 1, 'name' => 'John', 'email' => 'john@example.com'],
['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com'],
['id' => 3, 'name' => 'Bob', 'email' => 'bob@example.com'],
];
$names = array_column($users, 'name');
// Result: ['John', 'Jane', 'Bob']
Extract IDs
$ids = array_column($users, 'id');
// Result: [1, 2, 3]
Using Index Key
Index by Another Column
$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
];
$indexed = array_column($users, 'name', 'id');
// Result: [1 => 'John', 2 => 'Jane']
Create Lookup Array
$products = [
['id' => 1, 'name' => 'Product A', 'price' => 100],
['id' => 2, 'name' => 'Product B', 'price' => 200],
];
$lookup = array_column($products, 'price', 'id');
// Result: [1 => 100, 2 => 200]
// Use: $lookup[1] to get price of product 1
Real-World Examples
Database Results
$results = [
['id' => 1, 'title' => 'Post 1'],
['id' => 2, 'title' => 'Post 2'],
];
$titles = array_column($results, 'title');
$ids = array_column($results, 'id');
Create Options Array
$categories = [
['id' => 1, 'name' => 'Tech'],
['id' => 2, 'name' => 'Design'],
];
$options = array_column($categories, 'name', 'id');
// Result: [1 => 'Tech', 2 => 'Design']
// Use in select dropdown
Conclusion
array_column() is essential for:
- Extracting columns from multi-dimensional arrays
- Transforming data structures
- Creating lookup arrays
- Working with database results
Key Points:
- Extracts single column
- Can index by another column
- Works with associative arrays
- Useful for data transformation
Mastering array_column() simplifies working with structured data in PHP.
Written by Mahesh Waghmare
I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.
Follow on Twitter →