Pretty cool stuff for pretty cool people.

Menu

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:

PHP

1

2

3

4

5

6

<?php

$var=1;

//a lot of code goes here

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

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 notwork. 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:

PHP

1

2

3

4

5

<?php

$test=1;

$isScalar=is_scalar($test);

var_dump($isScalar);

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

PHP

1

2

3

4

5

<?php

$test=array(1,2,3);

$isScalar=is_scalar($test);

var_dump($isScalar);

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