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

This is a PHP error that will happen if you attempt to use a scalar value as an array.

In PHP, a scalar value is one unit of data. In other words, it is a variable that contains a string, an integer, or a float value.

More often than not, this warning happens because the developer has forgotten about the existence of a previously-declared scalar variable.

For example:

$var = 1;

//a lot of code goes here

$var['name'] = 'John';

As you can see, I completely forgot about the fact that I already had an integer variable called $var.

If I were to run the code above, my script would display an unappealing “Cannot use a scalar” warning.

It is extremely important to note that the code above will not work. In other words, $var will remain as an integer. The data that I tried to add to the “array” will be lost.

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

$test = 1;
$isScalar = is_scalar($test);
var_dump($isScalar);

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

However, if you run the following:

$test = array(1, 2, 3);
$isScalar = is_scalar($test);
var_dump($isScalar);

You will see that the result is FALSE.

It is also worth noting that null and non-existent variables will also return FALSE.