Using PHP's array_column() to Extract a Single Column from a Multidimensional Array

This article explains the PHP array_column() function, its parameters and return value, and provides a complete example showing how to extract the "first_name" column from a record set and display the resulting array of names.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP's array_column() to Extract a Single Column from a Multidimensional Array

The array_column() function returns the values from a single column of the input array. If the optional index_key is provided, the values from that column become the keys of the returned array.

Parameters

input : The multidimensional array (or result set) from which to pull a column.

column_key : The column to return; can be an integer index, a string key, or NULL to return the whole sub‑array.

index_key (optional): The column whose values will be used as keys in the returned array; can be an integer index or a string key.

Return value

An array containing the values from the specified column of the input array.

Example usage

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

Output

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTutorialarray_columnmultidimensional array
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.