Cannot use object of type stdClass as array¶
Description¶
The array syntax $variable[index]
is only available for arrays and strings. When used on objects, PHP emits a fatal error.
The boolean false
and the null
value still accept this behavior. The first is deprecated in PHP 8.1, and the second valid in PHP 8.3.
Example¶
<?php
$x = new Stdclass();
$x[0] = 1;
?>
Solutions¶
Check for type before using the array syntax.
Keep using consistent types with each variables.
Set type with properties to ensure they are consistent.
Cast the object to array before usage.
In previous PHP versions, this error message used to be Cannot unset offset in a non-array variable.