Re: [RFC] [Discussion] array_get and array_has functions
| From: | Larry Garfield | Date: | Mon, 20 Apr 2026 15:18:16 +0000 |
| Subject: | Re: [RFC] [Discussion] array_get and array_has functions | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-130674@lists.php.net to get a copy of this message | ||
On Sun, Apr 19, 2026, at 10:06 AM, Tim Düsterhus wrote:
> Hi
>
> Am 2026-04-18 08:06, schrieb Barel:
>> I am still unconvinced about this. Your proposal seems to give the
>>
null
>> a special value and I think that in general the full semantics are less
>
> null being a value indicating absence is by no means “special” in my
> suggestion. As previously mentioned, it's the semantics of
> isset().
> It's also what array_find() and
> array_find_key() return. It has
> special syntax in types with the questionmark in ?Type.
> It's what you
> get when you read a non-existent value.
>
>> clear. And I don't really like the function throwing errors for paths,
>> I
>> think that this function is great for defensive access to values, where
>> you
>> can be sure that you don't need to be checking the path all the time.
>> The
>
> Defensive access to me also implies throwing errors *where appropriate*,
> namely trying to perform an operation that is not meaningful. Trying to
> access an array offset on a string is not meaningful and trying to do
> *something* is not likely what the user intended to do. Similarly users
> passing in ArrayAccess objects might reasonably expect them to
> “just
> work”. Returning a default value instead of a clear error will likely
> lead to them thinking they found a bug in PHP.
Just to make sure we're talking about the same thing here. Tim, you're suggesting that
this:
$a = ['foo' => 'bar'];
$val = array_path_get($a, ['foo', 'bar', 'baz']);
Should error rather than returning null?
If so, then I do not agree. The purpose of these functions, as I see it, is for dealing with
inconsistently structured, wonky, arguably stupidly-designed data. (Which is a lot of REST APIs in
the wild, sadly.) If the array were clearly, consistently, and properly structured, we could
reliably just do $a['foo']['bar'] and move on with life. Or trivially convert
it to a properly typed object. These functions are for cases where those are not viable or
convenient options, meaning cases where a given value could be a string or an array, because the
data model author hates you. (As noted in a previous reply, I have run into such structures where
the value of a JSON key is string|string{}. It bloody well sucks..)
So in that sort of case, I'm not sure it's useful to distinguish between "There is no
baz key on the array at foo.bar" and "foo.bar is a string, not an array, wat?" If
that was a distinction that mattered, I'd be using ?? or converting to an object or whatever
else already.
--Larry Garfield