I was working on a WordPress plugin today and came across the most disturbing PHP warning error which I have never seen before in all the time that I’ve worked with PHP. The warning error message was :

Warning: Cannot use a scalar value as an array

What caused this error was when I tried to append an array key, value pair to a variable equal to zero (0). I retrieved the global WordPress variable $errors and attempted to append a key, value pair to the variable, though the variable type was invalid. The type was INT (because it was set to null) and it didn’t make sense to treat it as an array.

A solution to this would be to check if the variable is an array. In case it isn’t and it is empty, you can redefine it with the correct variable type. Usually, in PHP, this would not be the case and I cannot explain in detail exactly why this happened, but it had to have something to do with the fact that it was a pre-defined GLOBAL variable. So in my custom function, I did this :

function myfunction() {
	global $errors;

	if (!is_array($errors)) {
		$errors = array();
	}

	$errors['field_name'] = __('ERROR: Please fill in a value', $plugin_name);
}

And that fixed it! The warning error was gone and I am satisfied.