2

Colleague tells me that, in PHP, this is an unsafe selector.

$a = $some_array['foo']['bar'];

And that if ['bar'] has no value, $a will default to $some_array['foo']

Is this right?, because that doesn't seem right to me...

Comments
  • 8
    well - you _could_ just try it, you know. would've been faster than asking IMHO.

    or ask your colleague to demonstrate, if you want to expose them.

    but: no, that is no behavior i ever witnessed in PHP.
  • 0
    @tosensei I mean, I've tried it enough, and never had it happen, but I'm looking to respond with solid "no, you are fucking wrong, stop being a know-it-all" to his code review of that situation.
  • 4
    @dakkarant just tell him to actually reproduce the behavior he claims and be done with it.
  • 5
    @dakkarant I haven't seen a cowboy do this in years without at least a array_key_exists() before it.

    As to what actually happens, nothing.
    It's an undefined index and will error out.

    Otherwise an example of what he's talking about, especially how he defined "bar" in the first place would be good to see. "Bar" should still contain some kind of value or type regardless.

    Source: I've been doing php long enough to know what a php3 file is 🙃
  • 1
    @C0D4 So in php 3 this would have returned something instead of undefined?
  • 1
    The example is slightly misleading when $some_array is an object implementing __get to return some object also implementing __get to return the parent for non-existing keys.
  • 2
    @dakkarant it would have thrown an uninitialised array error from the hash checking alone. 'Bar' is not in 'foo'.

    If for some reason bar was not null, and didn't have a type for its value, it would return nothing without error. But how do you have a typeless type in C?

    Got to remember, php was a lot closer to C back then as it was written as a wrapper for C.

    After zend got involved it spread its wings further away with abstraction, but it's still a C wrapper regardless.
  • 2
    Seriously? No.

    The same thing would happen that happens when you drive without looking: you crash.

    I think his brain crashed, honestly.
  • 2
    @dakkarant

    What @CoD and @oktokolo said.

    An array will crap out on undefined index.

    Even if you suppress error output, the result will still be null.

    https://3v4l.org/#v4.3.0

    Has been, always will be - PHP 4.3.0 online via link, test it :)
Add Comment