Current Location: Home> Latest Articles> How to Use the PHP 5.5 array_column Function to Extract a Specific Column from a 2D Array

How to Use the PHP 5.5 array_column Function to Extract a Specific Column from a 2D Array

M66 2025-06-19

PHP 5.5 Function Guide: How to Use the array_column Function to Extract a Specific Column from a 2D Array

In PHP 5.5, the array_column

Parameter Explanation:

  • $input:The 2D array from which data will be extracted.
  • $column_key:The key or index of the column you want to extract.
  • $index_key (optional):The key or index that will be used as the keys of the returned array.

Example: Extracting Employee Names

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.

Defining the Employee Array

$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
)

Setting the Index Key

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
)

Conclusion

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.