Warning: Illegal string offset in PHP 5.4 [duplica

2019-01-20 06:29发布

This question already has an answer here:

I upgraded to PHP 5.4 today and I am receiving some strange warnings:

Warning: Illegal string offset 'quote1' in file.php on line 110
Warning: Illegal string offset 'quote1_title' in file.php on line 111

Those lines are this part of the code:

for($i = 0; $i < 3; $i++) {
    $tmp_url = $meta['quote'. ($i+1)];
    $tmp_title = $meta['quote' . ($i+1) .'_title'];

    if(!empty($tmp_url) || !empty($tmp_title)) {
        $quotes[$src_cnt] = array();
        $quotes[$src_cnt]['url'] = $tmp_url;
        $quotes[$src_cnt]['title'] = $tmp_title;
        $src_cnt++;
    }
}

So the $tmp_url and $tmp_title line.

Why am I receiving this odd warning and what is the solution?

Update:

This code is being used as a Wordpress plugin. $meta includes:

$meta = get_post_meta($post->ID,'_quote_source',TRUE);

So I am suspecting that whenever the quotes fields are empty, this warning appears. Is there any way that I can fix this for when the fields are empty?

2条回答
贪生不怕死
2楼-- · 2019-01-20 07:02

If $meta is null whenever there's no data to process:

if( !is_null($meta) ){
    for($i = 0; $i < 3; $i++) {
        // ...
    }
}

You should be able to do more checks if necessary. That depends on what that get_post_meta() function is designed to return.

查看更多
Rolldiameter
3楼-- · 2019-01-20 07:19

You need to make sure, that $meta is actually of type array. The warning explicitly tells you, that $meta seems to be a string and not an array

Illegal string offset
        ^^^^^^

To avoid this error you may also check for the needed fields

for($i = 0; $i < 3; $i++) {
    if ( !is_array($meta) || !array_key_exists('quote'. ($i+1), $meta) ){
         continue;
    }
    // your code
}
查看更多
登录 后发表回答