Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array stdClass Object - Echo Value

so I have this array saved in a variable title $arr. I want to grab or echo the value of [slug]

Array ( [0] => stdClass Object ( [term_id] => 11 
                                 [name] => Community Service 
                                 [slug] => community-service 
                                 [term_group] => 0 
                                 [term_taxonomy_id] => 11 
                                 [taxonomy] => category

So i want something like this

echo $arr[slug]

which would then display "community-service". I am sure this is something pretty easy but i can't figure out how to grab the value out of an array stdClass and echo it on the page. Thank you.

like image 848
user982853 Avatar asked May 21 '12 16:05

user982853


People also ask

How to Echo stdClass object in php?

Show activity on this post. $results = Array ( [0] => stdClass Object ( [title] => Title A [catid] => 1 ) [1] => stdClass Object ( [title] => Title B [catid] => 1 ) ); $str = ""; foreach($arr as $item) { $result . = $item->title .

How do I print a stdClass object?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


2 Answers

The array $arr contains 1 item which is an object. You have to use the -> syntax to access it's attributes.

echo $arr[0]->slug;

like image 196
ilanco Avatar answered Sep 20 '22 11:09

ilanco


Sorry, but you can do something more elegant.

foreach ($array as $obj)
{
    // Here you can access to every object value in the way that you want
    echo $obj->term_id;
}
like image 38
Pablo Ezequiel Leone Avatar answered Sep 19 '22 11:09

Pablo Ezequiel Leone