PHP – Warning: Cannot use a scalar value as an array.

This is a PHP error that happens whenever you attempt to use a scalar value as an array. In PHP (as well as in other languages), a scalar value is one unit of data. i.e. It is a variable that contains a string, an integer or a float value. More often than not, this warning is emitted because the developer in question has forgotten about the existence of a previously-declared scalar variable.

For example:

As you can see, I completely forgot about the fact that I had instantiated $var as an integer. If I were to run the code above, the result would be an unappealing “Cannot use a scalar” warning.

It is extremely important to note that the code above will not work. i.e. $var will remain as an integer and any data that you attempted to add to your “array” will be lost.

If you’re unsure about whether a certain variable is a scalar value or not, you can use the is_scalar function like so:

If run the code above, you’ll find that it returns a boolean TRUE value. However, if you run the following:

You’ll find that the result is FALSE. It is also worth noting that null / non-existent variables will also return FALSE.

Comments

comments