Master PHP’s array_column(): Extract Values from Multidimensional Arrays Easily
This guide explains PHP’s array_column() function—available since version 5.5—detailing its syntax, parameters, return value, and practical code examples that show how to extract specific keys from multidimensional arrays and optionally use another key as the resulting array’s index.
What is array_column()?
The array_column() function, introduced in PHP 5.5, extracts the values of a single column from a multidimensional array and returns them as a one‑dimensional array. It can also reindex the result using a specified key.
Syntax
array_column(array $input, mixed $column_key [, mixed $index_key = null])Parameters
$input (required): The multidimensional array to process.
$column_key (required): The key whose values you want to extract.
$index_key (optional): The key to use as the index/key in the returned array.
Return Value
A one‑dimensional array containing the values from the specified column. If $index_key is provided, the returned array is indexed by those values.
Basic Example
<?php
$users = [
['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Jane', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Smith', 'email' => '[email protected]'],
];
$names = array_column($users, 'name');
print_r($names);
// Result: Array ( [0] => John [1] => Jane [2] => Smith )
?>This code creates a multidimensional array of user data, then extracts the name column into $names and prints the resulting list.
Advanced Usage with Index Key
<?php
$users = [
[
'id' => 1,
'name' => 'John',
'email' => '[email protected]',
'age' => 25,
],
[
'id' => 2,
'name' => 'Jane',
'email' => '[email protected]',
'age' => 30,
],
[
'id' => 3,
'name' => 'Smith',
'email' => '[email protected]',
'age' => 35,
],
];
$result = array_column($users, 'name', 'id');
print_r($result);
// Result: Array ( [1] => John [2] => Jane [3] => Smith )
?>By specifying 'id' as the $index_key, the function returns an associative array where each user’s ID becomes the key and the name becomes the value.
Conclusion
The array_column() function is a concise and powerful tool for extracting specific fields from complex arrays in PHP, reducing boilerplate loops and improving code readability. Understanding its syntax and optional index parameter enables developers to manipulate data structures efficiently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
