How to fix this `Illegal string offset` error in php?

705

I have a multidimensional array as below:

$rows[] = $row;

Now I want to create variable from looping this array. This is how I tried it:

foreach ($rows as $k => $value) {
  //echo '<pre>',print_r($value).'</pre>';
  $id    = $value['news_id'];
  $title = $value['news_title'];
  echo $title; 
}

But it produce an error as below:

...... Illegal string offset 'news_id'

This is the output of -echo '<pre>',print_r($value).'</pre>';

Array
(
    [news_id] => 1110
    [news_title] => test
    [news] => test des
)
1

Array
(
    [news_id] => 1109
    [news_title] => ශ්‍රී ලංකාවේ ප්‍රථම....
    [news] => දහසක් බාධක....
)
1

Can anybody tell me what is the wrong I have done?

UPDATE output forecho '<pre>',print_r($rows).'</pre>';

Array
(
  [0] => 
  [1] => Array
      (
          [news_id] => 1110
          [news_title] => test
          [news] => test des
      )

  [2] => Array
      (
          [news_id] => 1109
          [news_title] => ශ්‍රී ලංකාවේ ප්‍රථම....
          [news] => දහසක් බාධක....        
      )

)
1
678

Answer

Solution:

useisset function because your 0 index is empty in$row

foreach ($rows as $k => $value) {
  if(isset($value['news_id'])){
    $id    = $value['news_id'];
    $title = $value['news_title'];
    echo $title; 
  }

}

you should add check (condition) when you assign data to$rows

People are also looking for solutions to the problem: php - iframe not inserting by editor role in WordPress

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.