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

1
  • The error message is quite clear: "Cannot use object [...] as array [...]". Commented Aug 14, 2012 at 19:08

3 Answers 3

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.

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

Comments

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!

Comments

1

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

Comments

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.