0

A function returns array of following type:

Array ( [0] => stdClass Object ( [post_id] => 48 

I want to echo the array contents, so i tried using following foreach loop:

foreach ($posts as $post){
    echo $post['post_id'];
}

But I get following error:

Fatal error: Cannot use object of type stdClass as array in

Rizier123
  • 58,877
  • 16
  • 101
  • 156
user1355300
  • 4,867
  • 18
  • 47
  • 71

3 Answers3

3

You have an array of objects. So, you need to change:

echo $post['post_id'];

To:

echo $post->post_id;

Now, you're printing the object property post_id.

nickb
  • 59,313
  • 13
  • 108
  • 143
2

If you're looking to output array or object information for something like debugging, you can do this:

echo '<pre>';
print_r($object);
echo '</pre>';

This should work for arrays or objects.

Also, I believe objects in PHP 5 have a "to_array" magic method that can convert an Object to an array of data.

I hope this helps!

jmbertucci
  • 8,194
  • 4
  • 50
  • 46
1

If you want to output for debugging purpose, you could use print_r or var_dump which is more verbose about your object.

Josejulio
  • 1,286
  • 1
  • 16
  • 30