PHP

Extract a Specific Column from an Array

Efficiently retrieve a single column of values from a multi-dimensional PHP array using `array_column`, ideal for processing database results or object lists.

<?php

$records = [
    ['id' => 101, 'first_name' => 'Alice', 'last_name' => 'Smith'],
    ['id' => 102, 'first_name' => 'Bob', 'last_name' => 'Johnson'],
    ['id' => 103, 'first_name' => 'Charlie', 'last_name' => 'Brown'],
];

// Extract all 'first_name' values
$firstNames = array_column($records, 'first_name');
// Result: ['Alice', 'Bob', 'Charlie']

// Extract 'last_name' values, using 'id' as the keys
$lastNamesById = array_column($records, 'last_name', 'id');
// Result: [101 => 'Smith', 102 => 'Johnson', 103 => 'Brown']

$usersWithAges = [
    ['name' => 'Dave', 'age' => 30],
    ['name' => 'Eve', 'age' => 25],
    ['name' => 'Frank', 'age' => 40],
];

// Extract 'age' values without specifying a key (defaults to indexed array)
$ages = array_column($usersWithAges, 'age');
// Result: [30, 25, 40]

echo "First Names: " . json_encode($firstNames) . "
";
echo "Last Names by ID: " . json_encode($lastNamesById) . "
";
echo "Ages: " . json_encode($ages) . "
";

?>
How it works: The `array_column()` function is a powerful tool for working with arrays of arrays (or objects). It allows you to extract all the values for a single key from each sub-array or object within a larger array. Optionally, you can specify a `key_index` to use values from another column as the keys in the resulting array, which is incredibly useful for creating lookup tables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs