Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3, PHP 8.4 With Latest All Version Support.
In PHP 8.1 & PHP 8.2 , the array_column() function is used to return the values from a single column in a multi-dimensional array (typically an array of arrays or an array of objects). It is very useful when working with arrays fetched from databases or APIs.
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
Parameters
$array = A multi-dimensional array from which to pull a column of values.
$column_key = The column of values to return. This can be an integer index or a string key. Use null to return the entire row.
$index_key = (Optional) The column to use as the index/keys for the returned array.
Example 1: Get column of names from an array
$data = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'] ]; $names = array_column($data, 'name'); print_r($names); Output: Array ( [0] => Alice [1] => Bob [2] => Charlie )
Example 3: Array of objects (PHP 7.0+ and 8.x)
$objects = [ (object)['id' => 101, 'email' => 'a@example.com'], (object)['id' => 102, 'email' => 'b@example.com'] ]; // Convert objects to arrays first $emails = array_column(array_map('get_object_vars', $objects), 'email'); print_r($emails);
Note:-
- array_column() only works on arrays, not directly on objects. Convert objects using get_object_vars().
- In PHP 8.2, the function behavior is consistent with earlier 7.x and 8.x versions.
- If the $column_key does not exist in a sub-array, null will be returned for that entry.
Let me know if you want examples using associative arrays, nested arrays, or database results.