- 🇭🇰Hong Kong graham leach
Hello,
In my experience, this error is the result of insufficiently "defensive" programming.
It occurs when PHP is asked to process something that lacks a *countable* property because what it is being presented with is NULL.
Objects that are NULL do not have a countable property, which is the nature of the error/notice given.
In previous versions of PHP, the [notice] error was not issued.
But, as the quality of PHP improved, the [notice] warning was added somewhere in PHP 7.
Here's an example of what would trigger that error:
function element_children(&$elements, $sort = FALSE) { foreach ($elements as $key => $value) { } }
Unfortunately, if the above function is passed a NULL array, a [notice] will be issued regarding the countable property.
To avoid this, implement "defensive" programming akin to what is being done these days to validate form input (i.e. assume the worst) to "sanitize" it:
function element_children(&$elements, $sort = FALSE) { if(!is_null($element) { foreach ($elements as $key => $value) { } } }
Also, for those who might not know, using "&$elements" passes a reference to the variable as it exists in memory, not a copy of it. This is indicated by the "&" character.
https://www.php.net/manual/en/language.references.pass.php
For the purposes of this explanation you can ignore the "&" character in the function definition and simply consider it as "$elements".
I have written a little paper on this aspect/shortcoming of Drupal Core. If you are interested to learn more, contact me.