In PHP 5.5, the array_column
Now, let’s walk through a practical example of how to use the array_column function. Suppose we have a 2D array containing employee information, and we want to extract all employee names.
$employees = array( array('Name' => 'Zhang San', 'Age' => 25, 'Salary' => 10000), array('Name' => 'Li Si', 'Age' => 30, 'Salary' => 15000), array('Name' => 'Wang Wu', 'Age' => 35, 'Salary' => 20000) );
We can now use the array_column function to extract the "Name" column:
$names = array_column($employees, 'Name');
The $names array will now contain all employee names, and we can print the result using:
print_r($names);
The output will look like this:
Array ( [0] => Zhang San [1] => Li Si [2] => Wang Wu )
In addition to extracting specific columns, the array_column function also allows you to set the keys of the returned array using the third parameter, $index_key. Let's continue using the $employees array and set the employee "Age" as the key for the returned array:
$names = array_column($employees, 'Name', 'Age');
Now, the returned $names array will use the employees' ages as keys and their names as values. The output will be:
Array ( [25] => Zhang San [30] => Li Si [35] => Wang Wu )
The array_column function is a very practical addition to PHP 5.5, allowing developers to quickly extract a specific column from a 2D array. By specifying the key or index, you can easily retrieve the data you need, and with the third parameter, you can also customize the keys of the returned array. This function helps developers handle and manipulate large datasets more efficiently and flexibly.