user1355300
user1355300

Reputation: 4987

PHP How to output the array content

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

Upvotes: 0

Views: 608

Answers (3)

Josejulio
Josejulio

Reputation: 1295

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

Upvotes: 1

jmbertucci
jmbertucci

Reputation: 8254

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!

Upvotes: 2

nickb
nickb

Reputation: 59709

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.

Upvotes: 3

Related Questions