Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Warning Illegal string offset in PHP

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

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

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:

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

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

Any help would be greatly appreciated!

like image 550
Jason Avatar asked Mar 09 '14 06:03

Jason


People also ask

What does illegal string offset mean PHP?

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.

What is a string offset?

Introduction. In most PHP functions, providing a negative value as string offset means 'n positions counted backwards from the end of the string'. This mechanism is widely used but, unfortunately, these negative values are not supported everywhere this would make sense.


3 Answers

Magic word is: 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';
}
like image 77
Adrian Preuss Avatar answered Oct 19 '22 04:10

Adrian Preuss


1.

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

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.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
like image 25
zion ben yacov Avatar answered Oct 19 '22 05:10

zion ben yacov


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';
}
like image 33
Vignesh Pichamani Avatar answered Oct 19 '22 05:10

Vignesh Pichamani