18

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..?

fusion3k
  • 11,568
  • 4
  • 25
  • 47
Stephen Last
  • 5,491
  • 9
  • 44
  • 85

1 Answers1

6

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'));
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • I don't know much about the PHP internals, but I think it is because of this: http://lxr.php.net/xref/PHP_7_0/ext/standard/array.c#3569 where it skips the "empty" PHP values. I also could be wrong – Rizier123 Apr 15 '16 at 09:04
  • 1
    @Rizier123 - that looks as though it would have the effect of eliminating any value that compares with null (and the bug also affects valid nulls and boolean false).... better to simply test if the property exists; I might do a PR this weekend – Mark Baker Apr 15 '16 at 09:07
  • Yes, that is what I meant with *"empty" PHP values* :) I also tested it with an empty string which didn't showed up in the result. Sadly I don't know enough about the internals that I could fix it. – Rizier123 Apr 15 '16 at 09:09
  • 1
    Also there seems to be other problems with `array_column()` in PHP 7 with objects: https://3v4l.org/tRnlr It does not see to work with integer properties. Same for invalid property names: https://3v4l.org/CDvPC – Rizier123 Apr 15 '16 at 09:12
  • 1
    How do you fix an elephpant? One bug at a time :) – Mark Baker Apr 15 '16 at 09:15
  • Voted on it. Seems like you are a bit more involved into the internals, so maybe this is interesting for you: http://stackoverflow.com/q/36246993 I'm not 100% sure if this is also a PHP bug or if I missed something there. – Rizier123 Apr 15 '16 at 14:02