PHP : Cannot use a scalar value as an array

Tue, Feb 26, 2008

PHP, WordPress, Wordpress Plugins

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’] = __(‘<strong>ERROR:</strong> Please fill in a value’, $plugin_name);
}

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

, , , , ,

This post was written by:

Antonie Potgieter - who has written 46 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

1 Comments For This Post

  1. doug b Says:

    I also had this problem. It’s due to Wordpress setting PHP’s error reporting level more strict than the default settings on your server. Most servers disable warnings since they’re not critical errors (won’t cause your script to die). Wordpress overrides these settings, and it does it in at least 7 locations. Get a decent editor like jedit and do a find in directory for the php function “error_reporting”. Comment out every one.

    There is absolutely no reason for Wordpress to do this, other than to assume that they’re the only thing you have running under PHP on that server. It’s bad form in my book.

Leave a Reply