0

I have a variable, "$terms", with the following contents/structure:

Array
(
[507] => stdClass Object
    (
        [term_id] => 507
        [name] => Blog
        [slug] => blog
        [term_group] => 0
        [term_taxonomy_id] => 679
        [taxonomy] => blog-category
        [description] => 
        [parent] => 0
        [count] => 3
        [object_id] => 13665
    )

[494] => stdClass Object
    (
        [term_id] => 494
        [name] => ZMisc
        [slug] => misc
        [term_group] => 0
        [term_taxonomy_id] => 662
        [taxonomy] => blog-category
        [description] => 
        [parent] => 0
        [count] => 5
        [object_id] => 13665
    )

)

I need to get the value of the first object's name. So in this instance, I need to retrieve the value of "Blog". This array is stored as $terms currently. I've tried $terms[0]->name among some other variants of this sytnax but can't quite get what I need.

JasonStockman
  • 532
  • 2
  • 4
  • 9
  • as you can see the objects are stored in 507 and 494 so you should try $terms[507]->name – Avner Solomon Jun 25 '13 at 23:56
  • duplicate http://stackoverflow.com/questions/6171699/cannot-use-object-of-type-stdclass-as-array-using-wordpress?rq=1 – Ronnie Jun 25 '13 at 23:58
  • I believe he means getting the first element of the array without knowing the index in advance. – David Lin Jun 26 '13 at 00:08
  • @Ronnie, the issue in the linked question is attempting to use `[]` on a `stdClass` instance. OP does not appear to have that problem, based on the reference to `->name` in the last sentence. – grossvogel Jun 26 '13 at 00:48

2 Answers2

1

There's many ways to do it:

current(reset($terms))->name;

reset($terms)->name; //thanks to comment from grossvogel, current is not needed

array_shift(array_values($terms))->name;

If you dont might modifying the original array, it can just as simple as

array_shift($terms)->name;
David Lin
  • 13,168
  • 5
  • 46
  • 46
  • 1
    +1 Note that the call to `current` in the first example is unnecessary, as [`reset`](http://php.net/manual/en/function.reset.php) already returns the first element. – grossvogel Jun 26 '13 at 00:46
  • Thanks mate, you taught me new things, I've been using reset function but never realised it returns the first element. – David Lin Jun 26 '13 at 01:02
  • reset worked perfect, thanks. Lots of new PHP functions to look into. Thanks all. – JasonStockman Jun 26 '13 at 01:07
0

In order to retrieve the first element of an array, you could do this:

var_dump(reset($terms));
Novak
  • 2,760
  • 9
  • 42
  • 63