A Quick Array Question

I have displayed the results of print_r($terms); as below:

Array
(
    [49] => stdClass Object
        (
            [term_id] => 49
            [name] => Fall 2014
            [slug] => fall-2014
            [term_group] => 0
            [term_taxonomy_id] => 61
            [taxonomy] => promo_category
            [description] => 
            [parent] => 0
            [count] => 12
            [object_id] => 622
            [filter] => raw
        )
)
1

So this is a multi-dimensional array that happens to only have one array element in it.

My question is: how do I access one of the elements in the inner array (or object?). For example, I want to access the ‘name’ and use it as an argument somewhere else.

I tried $terms[0]['name']

I also thought maybe $terms[0]->name because it is an object.

Am I close? Or what is the correct way of doing this? I’m not getting a value for either of these attempts.

Hi WebMachine,

Very close… you just need to use the correct array index, 49 rather than zero:

$terms[49]->name;

Okay, that makes sense - because 49 is the ‘key’ of this array. Thanks. So you can’t really mix associative arrays with indexed arrays in something multi-dimensional like this?

Okay, so this was a specific case. What if I didn’t know that the key of the first array was going to be 49, and I still want the access the ‘name’? Would I then go to a ‘foreach’ loop?

You could - there’s nothing to stop each item in the numeric array from being an associative array instead of an object. If you’re returning results from a DB query using PDO, for example, then calling fetchAll(PDO::FETCH_OBJ) will get you results a lot like your example above, whereas calling fetchAll(PDO:FETCH_ASSOC) would return a numeric array of associative arrays.

Yeah, that’s right.

$array = array();
$object = new stdClass();
$object->name = 'test';
$array[10] = $object;
$object = new stdClass();
$object->name = 'test';
$array[24] = $object;

now you dont know that the first key is 10 so you can easily just drop the keys

$newArray = array_values($array);

now $newArray has no longer they key 10 and 24 anymore but 0 and1 instead

As an aside, you can also get the first element of the array with [FPHP]reset[/FPHP] (non-consuming), or [FPHP]array_shift[/FPHP] (consuming).

You can also tell PHP to [FPHP]sort[/FPHP] a numeric array, which will render the keys into a 0-index. (NOTE: I… do not off the top of my head recall how PHP handles ambiguous sorting of a numeric array of objects. It will return a 0-indexed numeric array, but i’m not sure about the ordering of elements.)

1 Like

Thanks, @StarLion. Actually this is for determining the category name of a WordPress custom post type post which will only ever have one category assigned to it. So I only need to access the ‘name’ value of the first element in the array.