Illegal string offset Warning PHP

2018-12-31 04:35发布

I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

When I try to access it like this I get strange warnings

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

I really don't want to just edit my php.ini and re-set the error level.

标签: php warnings
12条回答
永恒的永恒
2楼-- · 2018-12-31 05:12

Before to check the array, do this:

if(!is_array($memcachedConfig))
     $memcachedConfig = array();
查看更多
怪性笑人.
3楼-- · 2018-12-31 05:17

Please try this way.... I have tested this code.... It works....

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r ($memcachedConfig['host']);
查看更多
泛滥B
4楼-- · 2018-12-31 05:17

The error Illegal string offset 'whatever' in... generally means: you're trying to use a string as a full array.

That is actually possible since strings are able to be treated as arrays of single characters in php. So you're thinking the $var is an array with a key, but it's just a string with standard numeric keys, for example:

$fruit_counts = array('apples'=>2, 'oranges'=>5, 'pears'=>0);
echo $fruit_counts['oranges']; // echoes 5
$fruit_counts = "an unexpected string assignment";
echo $fruit_counts['oranges']; // causes illegal string offset error

You can see this in action here: http://ideone.com/fMhmkR

For those who come to this question trying to translate the vagueness of the error into something to do about it, as I was.

查看更多
高级女魔头
5楼-- · 2018-12-31 05:19

There are a lot of great answers here - but I found my issue was quite a bit more simple.

I was trying to run the following command:

$x['name']   = $j['name'];

and I was getting this illegal string error on $x['name'] because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]:

$x = array();

and it worked.

查看更多
人间绝色
6楼-- · 2018-12-31 05:20

Just incase it helps anyone, I was getting this error because I forgot to unserialize a serialized array. That's definitely something I would check if it applies to your case.

查看更多
梦醉为红颜
7楼-- · 2018-12-31 05:22

It's an old one but in case someone can benefit from this. You will also get this error if your array is empty.

In my case I had:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname']; 

which I changed to:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
   echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname']; 
} else {
   echo 'Buyers id ' . $this_buyer_id . ' not found';
}
查看更多
登录 后发表回答