如何修复 PHP 中的警告非法字符串偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22279230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:47:41  来源:igfitidea点击:

How to fix Warning Illegal string offset in PHP

phparrayswordpresscastingoffset

提问by Jason

I have this chunk of PHP code which is giving me the error:

我有这块 PHP 代码,它给了我错误:

Warning: Illegal string offset 'iso_format_recent_works' in C:\xampp\htdocs\Manta\wp-content\themes\manta\functions.phpon line 1328

警告C:\xampp\htdocs\Manta\wp-content\themes\manta\functions.php中第1328行的非法字符串偏移量 'iso_format_recent_works'

This is the code that the warning is relating to:

这是与警告相关的代码:

if(1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

When I do an a var_dump($manta_option);I receive the follow result:

当我做 avar_dump($manta_option);我收到以下结果:

["iso_format_recent_works"]=> string(1) "1"

[“iso_format_recent_works”]=> 字符串(1)“1”

I have tried casting $manta_option['iso_format_recent_works']to an intbut still get the same issue.

我试过投射$manta_option['iso_format_recent_works']到 anint但仍然遇到同样的问题。

Any help would be greatly appreciated!

任何帮助将不胜感激!

回答by Adrian Preuss

Magic word is: isset

神奇的词是:isset

Validate the entry:

验证输入:

if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

回答by zion ben yacov

1.

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

回答by Vignesh Pichamani

Please check that your key exists in the array or not, instead of simply trying to access it.

请检查您的密钥是否存在于数组中,而不是简单地尝试访问它。

Replace:

代替:

$myVar = $someArray['someKey']

With something like:

像这样:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']
}

or something like:

或类似的东西:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';
}