Last Updated: Feb 3, 2025
Easy

PHP array_column() Function

Author Rahul Singh
0 upvote
Table of contents
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The PHP array_column() function is a built-in function that allows developers to extract a single column from a multi-dimensional array. It is useful when you need to pull out a specific field from an array of data, such as retrieving all values from a certain column in a table-like structure. This function simplifies the process of working with arrays, especially when dealing with large datasets.

PHP array_column() Function

In this article, you will learn about the syntax of the PHP array_column() function, how to use it to manipulate arrays, and best practices for implementing it in your PHP projects.

Definition and Usage  

The `array_column` function in PHP is used to extract a single column of values from a multi-dimensional array. It’s particularly useful when you have an array of arrays (like a list of users or products) & you want to extract out specific data, such as names or IDs, into a separate array.  

Syntax

array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
You can also try this code with Online PHP Compiler
Run Code

 

Explanation:

  • $array: The multi-dimensional array from which a column is to be extracted.
     
  • $column_key: The key/index of the column whose values need to be returned.
     
  • $index_key (optional): If provided, the function will use the values of this column as array keys in the returned array. 

Example  

Let’s say you have an array of users, where each user is represented as an associative array with keys like `id`, `name`, & `email`. You want to extract all the email addresses into a separate array.  

Let’s see how you can do it:  

<?php
// Sample multi-dimensional array
$users = [
    [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ],
    [
        'id' => 2,
        'name' => 'Jane Smith',
        'email' => 'jane@example.com'
    ],
    [
        'id' => 3,
        'name' => 'Alice Johnson',
        'email' => 'alice@example.com'
    ]
];
// Extract the 'email' column
$emails = array_column($users, 'email');
// Print the result
print_r($emails);
?>
You can also try this code with Online PHP Compiler
Run Code


Output  

Array
(
    [0] => john@example.com
    [1] => jane@example.com
    [2] => alice@example.com
)


In this example, `array_column` extracts all the values associated with the `email` key from the `$users` array & returns them as a new array.  

Parameters

  1. $array (Required): The input multi-dimensional array.
     
  2. $column_key (Required): The column index or name whose values need to be returned.
     
  3. $index_key (Optional): The column index or name whose values will be used as array keys in the returned array.

Return Type

  • The function returns an indexed or associative array containing values from the specified column.
     
  • If $index_key is provided, the returned array is associative; otherwise, it remains indexed.

Examples

Example 1: Extracting a Single Column

$students = [
    ["id" => 101, "name" => "Alice", "age" => 22],
    ["id" => 102, "name" => "Bob", "age" => 21],
    ["id" => 103, "name" => "Charlie", "age" => 23]
];

$names = array_column($students, "name");
print_r($names);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)

 

Explanation: Here, array_column() extracts the "name" column from the $students array and returns an indexed array.

Example 2: Using an Index Key

$students = [
    ["id" => 101, "name" => "Alice", "age" => 22],
    ["id" => 102, "name" => "Bob", "age" => 21],
    ["id" => 103, "name" => "Charlie", "age" => 23]
];

$namesWithID = array_column($students, "name", "id");
print_r($namesWithID);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [101] => Alice
    [102] => Bob
    [103] => Charlie
)

 

Explanation: The id column is used as the key, and the name column is used as the value, creating an associative array.

Example 3: Extracting a Column from a Nested Array

$products = [
    ["product" => "Laptop", "details" => ["price" => 1000, "brand" => "Dell"]],
    ["product" => "Phone", "details" => ["price" => 500, "brand" => "Samsung"]],
    ["product" => "Tablet", "details" => ["price" => 300, "brand" => "Apple"]]
];

$prices = array_column($products, "price", "product");
print_r($prices);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [Laptop] => 1000
    [Phone] => 500
    [Tablet] => 300
)

 

Explanation: The array_column() function does not work directly with nested keys. To fetch price, we need to access details["price"] separately.

Using the Optional `$index_key`  

You can also use the `$index_key` parameter to specify which column should be used as the keys in the resulting array. For example, if you want the `id` column to be the keys & the `email` column to be the values:  

<?php
// Extract 'email' column with 'id' as the index
$emails_with_id = array_column($users, 'email', 'id');
// Print the result
print_r($emails_with_id);
?>
You can also try this code with Online PHP Compiler
Run Code


Output  

Array
(
    [1] => john@example.com
    [2] => jane@example.com
    [3] => alice@example.com
)


Here, the `id` values (1, 2, 3) are used as keys in the resulting array.  

PHP Version  

The `array_column` function was introduced in PHP 5.5.0. If you’re using a version older than this, the function won’t be available, & you’ll need to upgrade your PHP installation to use it.  

Checking Your PHP Version  

Before using `array_column`, it’s a good idea to check your PHP version to ensure compatibility. You can do this by running a simple PHP script:  

<?php
// Check PHP version
echo 'Your PHP version is: ' . phpversion();
?>
You can also try this code with Online PHP Compiler
Run Code


When you run this script, it will display your current PHP version. If the version is 5.5.0 or higher, you can safely use `array_column`.  

Example of Compatibility  

Let’s say you’re working on a project & want to ensure your code runs smoothly across different PHP versions. You can add a check to see if `array_column` is available:  

<?php
// Check if array_column exists
if (function_exists('array_column')) {
    echo 'array_column is supported in your PHP version.';
} else {
    echo 'array_column is not supported. Please upgrade to PHP 5.5.0 or higher.';
}
?>
You can also try this code with Online PHP Compiler
Run Code


Output  

If your PHP version is 5.5.0 or higher, the output will be:  

array_column is supported in your PHP version.


If your PHP version is older, the output will be:  

array_column is not supported. Please upgrade to PHP 5.5.0 or higher.

Why Version Matters  

Using functions that aren’t supported in your PHP version can lead to errors & break your application. For example, if you try to use `array_column` in PHP 5.4 or lower, you’ll encounter a fatal error like this:  


Fatal error: Call to undefined function array_column()


To avoid such issues, always check your PHP version & ensure your server environment meets the requirements of the functions you’re using.  

Frequently Asked Questions

What happens if the $column_key does not exist in the array?

If the specified column key does not exist in the input array, array_column() will return an empty array.

Can array_column() be used with associative arrays?

Yes, array_column() works with both indexed and associative arrays. If an associative array is used, the extracted values will still be in an indexed format unless $index_key is specified.

Does array_column() preserve the original keys?

No, unless you provide an $index_key, the function re-indexes the output array starting from 0.

Conclusion

The array_column() function in PHP is a powerful tool for extracting specific columns from multi-dimensional arrays. It simplifies data retrieval and manipulation, making code cleaner and more efficient. By using this function effectively, developers can easily manage and filter large datasets.