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.

, , , , ,
banner3468x60png

This post was written by:

Antonie Potgieter - who has written 42 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

Leave a Reply