15

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.

Naveed
  • 41,517
  • 32
  • 98
  • 131
user982853
  • 2,470
  • 14
  • 55
  • 82

5 Answers5

48

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;

ilanco
  • 9,581
  • 4
  • 32
  • 37
8

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;
}
Pablo Ezequiel Leone
  • 1,337
  • 17
  • 22
1

Try simple following code...

echo $arr[0]->slug;

It supposed to be work because your array contain one object only.

tisuchi
  • 924
  • 1
  • 14
  • 18
0

It should work echo $arr->{0}->slug

George
  • 301
  • 2
  • 4
0

you can convert stdClass Object to php array like this and print any value.

$php_array = json_encode($stdClass_object);
$php_array = json_decode($php_array,true);
echo "<pre>";print_r($php_array);
Sandeep Sherpur
  • 2,418
  • 25
  • 27
  • Inefficient and unnecessary. Also PHP's on [some systems do not support JSON](https://stackoverflow.com/questions/18239405/php-fatal-error-call-to-undefined-function-json-decode) by default. – Mike Doe Dec 19 '18 at 11:05