maettig.com

Thiemos Archiv

I totally missed the new array_column() function that was introduced in PHP 5.5 in 2013. I wanted to explore it a bit.

For all the following examples, consider this two-dimensional array:

$array = [
    [ 'fruit' => 'banana', 'color' => 'yellow' ],
    [ 'fruit' => 'melon', 'color' => 'green' ],
];

You can think of it as a table with two numerically indexed rows, and two named columns. Your task is to extract all values from the »color« column into a numerically indexed array of strings:

[ 'yellow', 'green' ]

An oldskool, C-like solution for this might look like:

$colors = [];
for ( $i = 0; $i < count( $array ); $i++ ) {
    $colors[] = $array[$i]['color'];
}

Uh, wait. That's actually PHP 5.4, which introduced the short array syntax in 2012. Really classy PHP had to use array(), and looked more like this:

$colors = array();
for ( $i = 0; $i < count( $array ); $i++ ) {
    array_push( $colors, $array[$i]['color'] );
}

Another option is to iterate the array in a foreach() loop, which became much more stable and predictable with PHP 5.0:

$colors = [];
foreach ( $array as $data ) {
    $colors[] = $data['color'];
}

Since PHP 5.5, all of the above can now be replaced with:

$colors = array_column( $array, 'color' );

Neat! Ofcourse, the second argument can as well be an integer.

Bonus: It was also PHP 5.5 which introduced the possibility to use the list() syntax to unpack two-dimensional arrays right in the foreach() header. However, this was still limited to integer keys. It was PHP 7.1 which introduced the possibility to use string keys in the list() syntax, as well as to shorten list( … ) to [ … ]. This allows for:

$colors = [];
foreach ( $array as [ 'color' => $color ] ) {
    $colors[] = $color;
}

But wait, we are not done yet! array_column() does have a third, optional parameter named $index_key. What does it do?

$colors = array_column( $array, 'color', 'fruit' );

This returns:

[
    'banana' => 'yellow',
    'melon' => 'green',
]

If that's not handy, I don't know.

mehr schreiben


(Links wie gewohnt formatieren.)

[ ← Zurück zur Übersicht ]

Impressum & Datenschutz