Master PHP’s array_column(): Extract Values from Multidimensional Arrays Easily
This article explains the PHP 5.5+ array_column() function, detailing its syntax, parameters, return values, and provides clear code examples showing how to extract specific keys from multidimensional arrays and optionally use an index key to build associative arrays.
In PHP programming, the array_column() function (available from PHP 5.5.0) allows you to extract values of a specific key from a multidimensional array, returning a one‑dimensional array of those values.
Syntax
array_column(array $input, mixed $column_key [, mixed $index_key = null])Parameters
$input : required. Multidimensional array.
$column_key : required. The key to extract.
$index_key : optional. Used as the index/key of the returned array.
Return Value
Returns a one‑dimensional array containing the values from the specified column.
Code Example
Below is a simple example demonstrating how to use array_column() to extract the 'name' values from a multidimensional array of users.
<?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 )
?>Advanced Usage with Index Key
The function can also accept an $index_key to use a column as the keys of the returned array. The following example creates an associative array where user IDs are keys and names are values.
<?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 )
?>Conclusion
The array_column() function is a very useful and convenient tool that simplifies extracting specific key values from multidimensional arrays in PHP, enhancing code readability and efficiency.
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.
