Skip to content
Advertisement

Cannot use string offset as an array in php

I’m trying to simulate this error with a sample php code but haven’t been successful. Any help would be great.

“Cannot use string offset as an array”

Advertisement

Answer

For PHP4

…this reproduced the error:

$foo    = 'bar';
$foo[0] = 'bar';

For PHP5

…this reproduced the error:

$foo = 'bar';

if (is_array($foo['bar']))
    echo 'bar-array';
if (is_array($foo['bar']['foo']))
    echo 'bar-foo-array';
if (is_array($foo['bar']['foo']['bar']))
    echo 'bar-foo-bar-array';

(From bugs.php.net actually)

Edit,

so why doesn’t the error appear in the first if condition even though it is a string.

Because PHP is a very forgiving programming language, I’d guess. I’ll illustrate with code of what I think is going on:

$foo = 'bar';
// $foo is now equal to "bar"

$foo['bar'] = 'foo';
// $foo['bar'] doesn't exists - use first index instead (0)
// $foo['bar'] is equal to using $foo[0]
// $foo['bar'] points to a character so the string "foo" won't fit
// $foo['bar'] will instead be set to the first index
// of the string/array "foo", i.e 'f'

echo $foo['bar'];
// output will be "f"

echo $foo;
// output will be "far"

echo $foo['bar']['bar'];
// $foo['bar'][0] is equal calling to $foo['bar']['bar']
// $foo['bar'] points to a character
// characters can not be represented as an array,
// so we cannot reach anything at position 0 of a character
// --> fatal error
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement