PHP

Extract Column Values from Array of Arrays

Quickly extract all values from a specific column or key across multiple associative arrays or objects within a larger array using PHP's `array_column` function.

<?php

$records = [
    ['id' => 10, 'first_name' => 'John', 'last_name' => 'Doe'],
    ['id' => 20, 'first_name' => 'Jane', 'last_name' => 'Smith'],
    ['id' => 30, 'first_name' => 'Peter', 'last_name' => 'Jones'],
];

// Extract all 'first_name' values
$firstNames = array_column($records, 'first_name');
print_r($firstNames);

echo "
";

// Extract 'id' values, using 'first_name' as the index/key for the new array
$idIndexedByFirstName = array_column($records, 'id', 'first_name');
print_r($idIndexedByFirstName);

/* Output:
Array
(
    [0] => John
    [1] => Jane
    [2] => Peter
)

Array
(
    [John] => 10
    [Jane] => 20
    [Peter] => 30
)*/
How it works: The `array_column()` function in PHP is designed to return the values from a single column in the input array, identified by the `column_key`. This snippet shows two common uses. First, it extracts all `first_name` values into a simple indexed array. Second, it extracts the `id` values, but instead of using default numeric indices, it uses the `first_name` values as the keys for the new array, demonstrating the optional `index_key` parameter. This is highly efficient for quickly pulling specific data from structured arrays.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs