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\"
When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));
then it shows this fatal error Cannot use string offset as an object in
.
If you print like this
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
You won't get the error!!
I was having this error and a was nuts
my code was
$aux_users='';
foreach ($usuarios['a'] as $iterador) {
#code
if ( is_numeric($consultores[0]->ganancia) ) {
$aux_users[$iterador]['ganancia']=round($consultores[0]->ganancia,2);
}
}
after changing $aux_users='';
to $aux_users=array();
it happen to my in php 7.2 (in production server!) but was working on php 5.6 and php 7.0.30 so be aware! and thanks to Young Michael, i hope it helps you too!
I had this error for the first time ever while trying to debug some old legacy code, running now on PHP 7.30. The simplified code looked like this:
$testOK = true;
if ($testOK) {
$x['error'][] = 0;
$x['size'][] = 10;
$x['type'][] = 'file';
$x['tmp_name'][] = 'path/to/file/';
}
The simplest fix possible was to declare $x as array() before:
$x = array();
if ($testOK) {
// same code
}
I was fighting a similar problem, so documenting here in case useful.
In a __get()
method I was using the given argument as a property, as in (simplified example):
function __get($prop) {
return $this->$prop;
}
...i.e. $obj->fred
would access the private/protected fred property of the class.
I found that when I needed to reference an array structure within this property it generated the Cannot use String offset as array error. Here's what I did wrong and how to correct it:
function __get($prop) {
// this is wrong, generates the error
return $this->$prop['some key'][0];
}
function __get($prop) {
// this is correct
$ref = & $this->$prop;
return $ref['some key'][0];
}
Explanation: in the wrong example, php is interpreting ['some key']
as a key to $prop
(a string), whereas we need it to dereference $prop in place. In Perl you could do this by specifying with {} but I don't think this is possible in PHP.
The error occurs when:
$a = array();
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';
Then
echo $a['text1']['text2']; //Error!!
Solution
$b = $a['text1'];
echo $b['text2']; // prints: sometext
..
Since the release PHP 7.1+, is not more possible to assign a value for an array as follow:
$foo = "";
$foo['key'] = $foo2;
because as of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.