Current Location: Home> Latest Articles> Detailed Guide and Practical Examples of PHP array_column() Function

Detailed Guide and Practical Examples of PHP array_column() Function

M66 2025-07-10

Introduction to PHP array_column() Function

In PHP development, it is common to extract values of a specific key from a multidimensional array. The array_column() function is designed precisely for this purpose. Introduced in PHP version 5.5.0, it efficiently extracts a single column of values from a multidimensional array and returns them as a one-dimensional array.

Syntax and Parameters of array_column()

The basic syntax is as follows:

<span class="fun">array_column(array $input, mixed $column_key [, mixed $index_key = null])</span>
  • $input: Required, the input multidimensional array.
  • $column_key: Required, the key of the column to extract.
  • $index_key: Optional, the key to use as the index/keys for the returned array.

The function returns a one-dimensional array containing the values of the specified column. If $index_key is specified, its corresponding values are used as the keys of the returned array.

Basic Example: Extracting Values of a Specific Key

<?php
$users = [
    ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'],
    ['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com'],
    ['id' => 3, 'name' => 'Smith', 'email' => 'smith@example.com'],
];

// Extract all 'name' values
$names = array_column($users, 'name');
print_r($names);
// Output: Array ( [0] => John [1] => Jane [2] => Smith )
?>

This example quickly extracts all user names into a one-dimensional array using array_column().

Advanced Usage: Using a Specific Key as Index

<?php
$users = [
    ['id' => 1, 'name' => 'John', 'email' => 'john@example.com', 'age' => 25],
    ['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com', 'age' => 30],
    ['id' => 3, 'name' => 'Smith', 'email' => 'smith@example.com', 'age' => 35],
];

// Use 'id' as keys and 'name' as values to create an associative array
$result = array_column($users, 'name', 'id');
print_r($result);
// Output: Array ( [1] => John [2] => Jane [3] => Smith )
?>

In this example, the $index_key parameter is set to use user IDs as the keys of the resulting array, making it convenient to access names by ID.

Conclusion

The array_column() function is a powerful and convenient tool for handling multidimensional arrays in PHP. It simplifies extracting specific columns of data, improving code readability and performance. Mastering its use helps developers efficiently manipulate data collections.

References

  • Official PHP Manual: array_column function documentation