0
0
PhpHow-ToBeginner · 3 min read

How to Use array_column in PHP: Syntax and Examples

Use array_column in PHP to extract values from a specific column in a multi-dimensional array. It takes the input array, the column key to extract, and an optional index key to re-index the result array.
📐

Syntax

The array_column function extracts values from a single column in a multi-dimensional array.

  • array: The input multi-dimensional array.
  • column_key: The key or index of the column to extract.
  • index_key (optional): The key to use as the index for the returned array.
php
array_column(array $array, string|int|null $column_key, string|int|null $index_key = null): array
💻

Example

This example shows how to extract the 'name' column from an array of users and optionally use the 'id' as keys in the result.

php
<?php
$users = [
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 30],
    ['id' => 3, 'name' => 'Charlie', 'age' => 35],
];

// Extract names only
$names = array_column($users, 'name');
print_r($names);

// Extract names with ids as keys
$names_with_ids = array_column($users, 'name', 'id');
print_r($names_with_ids);
?>
Output
Array ( [0] => Alice [1] => Bob [2] => Charlie ) Array ( [1] => Alice [2] => Bob [3] => Charlie )
⚠️

Common Pitfalls

Common mistakes include:

  • Using a column_key that does not exist in the sub-arrays, which returns an array of null values.
  • Using an index_key that is not unique, causing keys to be overwritten.
  • Passing a non-array or malformed array as input.
php
<?php
// Wrong: column_key does not exist
$users = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
];
$result = array_column($users, 'nickname');
print_r($result); // Outputs array with null values

// Right: use existing column_key
$result = array_column($users, 'name');
print_r($result);
Output
Array ( [0] => [1] => ) Array ( [0] => Alice [1] => Bob )
📊

Quick Reference

ParameterDescriptionExample
arrayInput multi-dimensional array[['id'=>1,'name'=>'A'], ['id'=>2,'name'=>'B']]
column_keyKey of the column to extract'name'
index_keyOptional key for indexing result'id'
ReturnArray of extracted values['A', 'B'] or [1=>'A', 2=>'B']

Key Takeaways

Use array_column to quickly extract values from a specific column in a multi-dimensional array.
The optional index_key lets you re-index the result array with keys from the input array.
Ensure the column_key exists in all sub-arrays to avoid null values in the result.
Avoid duplicate keys in index_key to prevent overwriting values.
array_column returns a new array and does not modify the original array.