[wp-trac] [WordPress Trac] #43619: Introduce new PHP cross-version compat function `is_iterable()`
WordPress Trac
noreply at wordpress.org
Fri Mar 23 14:03:23 UTC 2018
#43619: Introduce new PHP cross-version compat function `is_iterable()`
-------------------------+-----------------------------
Reporter: jrf | Owner:
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version: trunk
Severity: normal | Keywords:
Focuses: |
-------------------------+-----------------------------
Similar to and related to #43583
PHP 7.2 introduced a warning when count() is used on something non-
countable.
PHP 7.1 introduced a new function called `is_iterable()` which basically
checks:
{{{#!php
if (is_array($foo) || $foo instanceof Traversable) {
// $foo is traversable
}
}}}
See: http://php.net/manual/en/function.is-iterable.php
When `count()` is used to check if an array is traverable, i.e. usable in
a `foreach(){}`, it would be better to replace the `count()` check with a
call to `is_iterable()`.
To that end, I would like to suggest adding this new function to the `wp-
includes/compat.php` file, like so:
{{{#!php
if ( ! function_exists( 'is_iterable' ) ) :
function is_iterable( $var ) {
return ( ( is_array( $var ) && ! empty( $var ) || $var
instanceof Traversable );
}
}
endif;
}}}
This seems like low hanging fruit. Both the `instanceof` operator as well
as the `Traversable` interface were already available in PHP 5.2.4, so
there should be no cross-version compatibility issues with introducing
this function.
The function would provide an easy helper function to help fix the various
issues where the warning is currently being reported - both for Core as
well as for plugin/theme devs -.
Existing code like this:
{{{#!php
if ( count( $var ) > 0 ) {
foreach( $var as $key => $value) {
// Do something.
}
}
}}}
can then be replaced by:
{{{#!php
if ( is_iterable( $var ) ) {
foreach( $var as $key => $value) {
// Do something.
}
}
}}}
The function would also still allow for code refactoring from arrays to
objects. /cc @schlessera
I would suggest introducing this function ASAP and not to wait for a major
release.
Related issues (there are probably more, but a quick search yielded
these):
#43583, #43374, #43368, #43312, #43216, #43201, #43216, #43201, #42860,
#42814, #42147, #42498
--
Ticket URL: <https://core.trac.wordpress.org/ticket/43619>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list