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.

4
  • as you can see the objects are stored in 507 and 494 so you should try $terms[507]->name Commented Jun 25, 2013 at 23:56
  • duplicate stackoverflow.com/questions/6171699/… Commented Jun 25, 2013 at 23:58
  • I believe he means getting the first element of the array without knowing the index in advance. Commented Jun 26, 2013 at 0: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. Commented Jun 26, 2013 at 0:48

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Note that the call to current in the first example is unnecessary, as reset already returns the first element.
Thanks mate, you taught me new things, I've been using reset function but never realised it returns the first element.
reset worked perfect, thanks. Lots of new PHP functions to look into. Thanks all.
0

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

var_dump(reset($terms));

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.