Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_column() not returning object falsy values

Tags:

php

php-7

I'm sure this is expected behavior for array_column():

class myObj {
    public $prop;
    public function __construct(int $prop) {
        $this->prop = $prop;
    }
}

$objects = [
    new myObj(7),
    new myObj(3),
    new myObj(8),
    new myObj(0),
    new myObj(2),
    new myObj(6)
];

echo '<pre>';
print_r(array_column($objects, 'prop'));
echo '</pre>';

Returns:

Array (
    [0] => 7
    [1] => 3
    [2] => 8
    [3] => 2
    [4] => 6
)

The 0 is missing. Maybe it uses empty() internally..?

Why would it not return falsy values when 0 and false can be normal valid object property values, and array_column() is meant for returning values..?

What's the best work around..?

like image 226
Stephen Last Avatar asked Apr 15 '16 08:04

Stephen Last


1 Answers

It certainly seems like a bug, and I'd report it as such

You can work round it by converting the object array to a nested array:

print_r(array_column(json_decode(json_encode($objects), true), 'prop'));
like image 72
Mark Baker Avatar answered Oct 12 '22 09:10

Mark Baker