1

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 for echo '<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
8
  • 1
    @BilalAhmed we can use that comma for it. Commented Sep 24, 2018 at 11:23
  • @BilalAhmed Does not matter at all. Commented Sep 24, 2018 at 11:24
  • Please add this to your code and put the result here: echo "<pre>" . print_r($rows) . "</pre>"; Because your syntax (array['index']) works for me. I would like to see how $rows is created. Commented Sep 24, 2018 at 11:29
  • 1
    Ok thanks. So $rows[0]['news_id'] does not exist. Add a check if (isset($value['news_id'])) { ... } Commented Sep 24, 2018 at 11:34
  • 1
    Possible duplicate of Illegal string offset Warning PHP Commented Sep 24, 2018 at 11:47

1 Answer 1

2

use isset 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

Sign up to request clarification or add additional context in comments.

2 Comments

The error Illegal string offset 'news_id' tells that $value is a string and 'news_id' is an illegal index, this may suppress error but not explaining what is wrong or how to fix it.
0th index doesn't need to be empty, simply being a string instead of an array would suffice. Let $rows = array('key' => array('news_id' => 'foo', 'news_title' => 'bar'), 'key1' => array('news_id' => 'foo', 'news_title' => 'bar'), 'key2' => array('news_id' => 'foo', 'news_title' => 'bar'), 'key3' => 'I am a simple string') , then trraversing this array with a foreach loop and checking $value['news_title'] will simply fail with Illegal string offset 'news_id' .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.