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

4
  • 1
    Seems like a bug for me. Commented Apr 15, 2016 at 8:54
  • which PHP version? Commented Apr 15, 2016 at 8:58
  • PHP 7.0.0 on Windows/IIS... Commented Apr 15, 2016 at 8:59
  • Reproduced on PHP 7.0.4 in Ubuntu Commented Apr 15, 2016 at 9:02

1 Answer 1

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'));
Sign up to request clarification or add additional context in comments.

6 Comments

I don't know much about the PHP internals, but I think it is because of this: 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 - 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
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.
Also there seems to be other problems with array_column() in PHP 7 with objects: 3v4l.org/tRnlr It does not see to work with integer properties. Same for invalid property names: 3v4l.org/CDvPC
How do you fix an elephpant? One bug at a time :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.