How could you create the array_column function in versions prior to PHP 5.5

Asked

Viewed 137 times

1

According to the PHP Handbook, the function array_column is available from 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);

Upshot:

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

However 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 you develop a function that did the same thing in previous versions of PHP?

1 answer

3


It is possible to implement the method array_column using the function array_map:

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

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

Therefore, to circumvent this limitation of previous versions of PHP 5.3 in support of anonymous functions, we may also use foreach to obtain this functionality:

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

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

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

    return $new;
}
  • 1

    +1 I liked the function. It was very simple. In this case, the only thing there that is not supporting before the 5.3 versions are the Closures

  • Well noted. I changed the answer.

  • 1

    If I may, I added an "additional bonus"

  • Of course. No foreach it is worth checking if the key exists, but this is topic for another question. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.