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 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
Closure
s– Wallace Maxters
Well noted. I changed the answer.
– Rodrigo Rigotti
If I may, I added an "additional bonus"
– Wallace Maxters
Of course. No
foreach
it is worth checking if the key exists, but this is topic for another question. :)– Rodrigo Rigotti