Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use string offset as an array in php

Tags:

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"

like image 342
rampr Avatar asked Dec 09 '09 13:12

rampr


Video Answer


1 Answers

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 
like image 54
Björn Avatar answered Sep 23 '22 13:09

Björn