First of all you must understand that every error message PHP generates is meant to help you, and to make your code cleaner and less error-ridden.
When your code contains a bug, your best bet is to fix it, not to brush it off. Most answers here helps you with the latter. But you should really consider doing the former.
Every error message helps you to find a bug in the code. It means that errors shouldn't be intentional or "habitual". This way you won't have to silence them, and every error will mean that your code indeed encountered a bug.
Like in your case. You are using count()
not on purpose. Not to actually count any values but only to tell whether returned value is empty or not. For this, you can use the variable itself:
if ($admin)
which is perfectly valid in PHP. Or, if you want to be more Catholic than the Pope, you can make it more strict but still on purpose
if ((bool)$admin === true)
So you should do every time when a function may return either false
or array
. This way, when accessing the returned value inside if
, you will never get an error related to improper use of arrays. Unless the returned value will be non-empty and not an array - a situation for which this error message was invented exactly for!
So just make sure that every function that should return an array, returns an array, or any variable that should contain an array, contains an array. And you won't see this error again. Unless, due to some error, your code will return a non-array value unexpectedly. And this error message will help you to pinpoint this problem.
When things are not under your control, like, you need to get an array from an outside variable, do a validation first. For example, in case you are expecting an array from a form, that is obligatory, validate it and return an error, like
if (!$isset($_POST['options']) || !is_array($_POST['options'])) {
// inform the user ad stop execution
} else {
$options = $_POST['options'];
}
// now you can safely use count() on $options
In case the array is optional, you may initialize it as empty array:
if (!$isset($_POST['options'])) {
$options = [];
} elseif (!is_array($_POST['options'])
// inform the user ad stop execution
} else {
$options = $_POST['options'];
}
// now you can safely use count() on $options
And only as a last resort you may silence this error, using a condition like this
count((is_countable($admin) ? $admin :[]))
or casting offered below