我得到一个奇怪的PHP错误后更新我的PHP版本到5.4.0-3。

我有这样一个数组:

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

当我试图像这样访问它时,我会得到奇怪的警告

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


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

我真的不想只是编辑我的php.ini并重新设置错误级别。


当前回答

为PHP

//Setup Array like so
$memcachedConfig = array(
  "host" => "127.0.0.1",
  "port" => "11211"
);

//Always a good practice to check if empty

if(isset($memcachedConfig['host']) && isset($memcachedConfig['port'])){

    //Some codes

    print_r ($memcachedConfig['host']);
    print_r ($memcachedConfig['port']);

}

只要确保返回的值不为空。 这个例子是PHP的看看如何在其他语言中检查数组是否为空。

其他回答

错误非法字符串偏移'whatever'在…通常意味着:你试图使用一个字符串作为一个完整的数组。

这实际上是可能的,因为字符串在php中可以被视为单个字符的数组。所以你认为$var是一个带键的数组,但它只是一个带标准数字键的字符串,例如:

$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

你可以在这里看到它的作用: http://ideone.com/fMhmkR

对于那些遇到这个问题试图将错误的模糊性转化为解决它的方法的人,就像我一样。

请尝试这种方式....我已经测试了这个代码....它的工作原理……

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);

只使用

$memcachedConfig = array();

之前

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


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

这是因为你从来没有定义什么是$memcachedConfig,所以默认情况下处理字符串而不是数组。

这对我来说很管用:

我的测试代码:

$var2['data'] = array ('a'=>'21','b'=>'32','c'=>'55','d'=>'66','e'=>'77');
foreach($var2 as $result)
{  
    $test = $result['c'];
}
print_r($test);

输出:55

看看吧,伙计们。谢谢

这个问题有点晚了,但对于其他正在搜索的人来说:我通过使用错误的值(类型)初始化得到了这个错误:

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

正确的做法是:

 $varName = array();
 $varName["x"] = "test"; // works