New PHP Polyfills in 4.9.6

It is considered good practice to validate variables before using them. As using type declarations is still very rare in the WordPress world, parameters passed in to functions may not be of the variable type expected. Similarly, the type of variable returned by a filter may have changed due to incorrect usage of the filter by plugins or themes.

One particular situation which causes bugs often is counting something which isn’t countable. Proper variable validation can prevent those bugs.

In PHP 7.2, a warning was introduced when count() is used on an uncountable value. PHP 7.3 will introduce the  function is_countable(), which will help prevent this warning by checking that the passed variable is actually countable (the RFC has passed the vote and the function has already been implemented and merged into PHP Core).

Using count() to detect if a value is iterable (able to be passed to a foreach() loop, for example), is also a common practice. However, this will also result in warnings when upgrading to PHP 7.2. In PHP 7.1, the is_iterable() function was introduced to help prevent these warnings.

To help WordPress Core, plugins, and themes be forwards compatible, a polyfill for each of these functions has been added in 4.9.6. When a site is not running a version of PHP that includes these functions, WordPress will automatically load these polyfills.

Checking A Value Is Countable

is_countable() was introduced in #43583.

Old Way

if ( count( $var ) > 0 ) {
        // Do something.
}

New Way

if ( is_countable( $var ) && count( $var ) > 0 ) {
        // Do something.
}

Checking A Value Is Iterable

is_iterable() was introduced in #43619.

Old Way

if ( count( $var ) > 0 ) {
        foreach( $var as $key => $value) {
                // Do something.
        }
}

New Way

if ( is_iterable( $var ) ) {
        foreach( $var as $key => $value) {
                // Do something.
        }
}

Updating Core

New tickets should be opened on Trac for instances in Core that would benefit from these new functions on a case by case basis. Since all instances of count() and foreach() should be verified, a meta ticket has been opened to keep track of which files have been checked (#44123).

Want to learn how to write better conditions?

To better understand how variables behave in various PHP versions, how to write better conditions, and to improve variable validation, you may like the PHP Cheat Sheets website.

#4-9-6, #dev-notes