Re: [RFC] Add is_list(mixed $value): bool to check for list-like arrays
| From: | tyson andre | Date: | Tue, 22 Dec 2020 01:05:19 +0000 |
| Subject: | Re: [RFC] Add is_list(mixed $value): bool to check for list-like arrays | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-112584@lists.php.net to get a copy of this message | ||
Hi Ben,
> I think there are some places where
is_list() could be
> unintuitive to
> those who don’t understand some of the idiosyncrasies of PHP.
>
> For example, with
>
> $a = ['foo', 'bar', 'baz’];
>
> is_list() will return true, but
> if you run $a through asort(),
> is_list() will return false
> because the keys are no longer
> consecutive integers, but is there any doubt this is still a list?
> Maybe in a pure sense, it’s not, but I think this could be confusing.
>
> But now, if we do
>
> $b = array_merge($a, ['qux', 'quux']);
>
> $b is now back to being a list, so
> is_list($b) returns true.
Yes, that's correct.
These idiosyncrasies of php and unintuitive behaviors existed
prior to this RFC.
It's also confusing when reset($x) is not the same thing as $x[0]
on a non-empty array with keys 0..n-1 out of order if you're still learning php.
> While I understand the convenience is_list() provides--I myself
> have
> implemented the opposite of this numerous times (e.g.,
> is_dict())--it comes close to implying a data type that PHP
> doesn’t
> have, and I think this could give a false sense of type-safety-ness
> when using this function to check whether something is a 0-indexed
> array.
It would simplify is_dict(array $x) to count($arr) > 0 &&
!is_list($arr),
and potentially improve performance.
There's already some ways is_* doesn't correspond to a data type
- is_numeric does not correspond to a data type.
- is_callable varies depending on the context where it's called for private
methods.
- is_resource returns false if a resource is closed.
- is_file is checking for a path (and readability?) on disk, not a type.
If you do understand what the type checks are doing, it makes it easier to check type-safety-ness
in a script (e.g. if(!is_list(...)){ /*warn*/ } in a standalone script) or with
external analyzers.
Thanks,
Tyson