when to use array_column with examples ? in php

array_column function in PHP is used to get the values from a single column of a multi-dimensional array.

Here is an example to demonstrate the usage of array_column:

main.php
// Sample multi-dimensional array
$users = [
    ['id' => 1, 'name' => 'Alice', 'age' => 30],
    ['id' => 2, 'name' => 'Bob', 'age' => 25],
    ['id' => 3, 'name' => 'Charlie', 'age' => 35]
];

// Get values from the 'name' column
$names = array_column($users, 'name');
print_r($names);

// Output:
// Array
// (
//     [0] => Alice
//     [1] => Bob
//     [2] => Charlie
// )
379 chars
19 lines

In this example, array_column($users, 'name') selects the values from the 'name' column of the $users array. You can also specify a key as the second argument to get the values of that specific key from the array.

This function is useful when you want to extract values from a column in a multidimensional array, for instance when you need to extract a list of names, IDs, or any other attribute from an array of records.

Remember, array_column requires PHP 5.5 or higher.

related categories

gistlibby LogSnag