How could I create the array_column function in versions earlier than PHP 5.5

1

According to the PHP Manual, array_column function is available from of PHP 5.5

It returns the value of a "column" of a multidimensional array in a single array.

Example:

$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);

Result:

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

But it is not present in versions prior to PHP 5.5 and this is a very good function to simplify an array structure when needed.

How could I develop a function that did the same thing in earlier versions of PHP?

    
asked by anonymous 08.09.2015 / 17:36

1 answer

3

You can implement the array_column method using the array_map function:

function array_column(array $array, $column) 
    return array_map(function($row) use($column) {
        return $row[$column];
    }, $array);
}

The array_map function is supported since PHP 4; but closures (anonymous functions), as well noted by Wallace Maxters, are supported only from PHP 5.3. So this code works in PHP versions> = 5.3 and < 5.5.

So, in order to circumvent this limitation of earlier versions of PHP 5.3 in support of anonymous functions, we can also use foreach to get this functionality:

function array_column(array $array, $column)
{
    $new = array();

    foreach ($array as $key => $value) {

        $new[] = $value[$column];
    }

    return $new;
}
    
08.09.2015 / 17:58