Array_column – Returns a column specified in an array

Description:

array_column ( array $input , mixed $column_key ,   mixed $index_key = null ) : array
Copy the code

Array_column () returns the column in the input array whose key is column_key. If the optional argument index_key is specified, the value of this column in the input array will be the key of the corresponding value in the returned array.

Parameter: **

Input: The multidimensional array that needs to be retrieved from the array column. If you provide an array of objects, only the public properties are fetched directly. In order to also extract private and protected properties, the class must implement the __get() and __isset() magic methods.

Column_key: The column whose value is to be returned. It can be a column index of an indexed array, a column key of an associative array, or a property name. It can also be null, which returns the entire array (useful with the index_key argument to reset the array key).

Index_key: The column that is the index/key of the returned array. It can be the integer index of that column, or the string key value.

The return value:

Returns a single-column array from a multidimensional array.

Example:

Example 1

<? php // Array representing a possible record set returned from a database $records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe', ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith', ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones', ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe', ) ); $first_names = array_column($records, 'first_name'); print_r($first_names); ? >Copy the code

Output:

Array(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)
Copy the code

Example 2:

<? php // Using the $records array from Example #1 $last_names = array_column($records, 'last_name', 'id'); print_r($last_names); ? >Copy the code

Output:

Array(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)
Copy the code

Example 3:

<? php class User{ public $username; public function __construct(string $username){ $this->username = $username; } } $users = [ new User('user 1'), new User('user 2'), new User('user 3'), ]; print_r(array_column($users, 'username')); ? >Copy the code

Output:

Array(
    [0] => user 1
    [1] => user 2
    [2] => user 3
)
Copy the code

Example 4:

<? php class Person{ private $name; public function __construct(string $name){ $this->name = $name; } public function __get($prop){ return $this->$prop; } public function __isset($prop) : bool{ return isset($this->$prop); } } $people = [ new Person('Fred'), new Person('Jane'), new Person('John'), ]; print_r(array_column($people, 'name')); ? Array([0] => Fred [1] => Jane [2] => John)Copy the code

If __isset() is not provided, an empty array is returned.