user712027
user712027

Reputation: 572

How do I access an array element in a multidimensional array?

Here's a representation of my array:

    $arr
    [0]
    [code]='a code'
    [number]='a number'
    [1]
    [code]='a code'
    [number]='a number'
    [2]
    [code]='a code'
    [number]='a number'
    [3]
    .
    .

I'm doing a foreach loop to get all the [code] values am stuck: I forgot how to do it. Can anyone please help me with it?

Upvotes: 1

Views: 75

Answers (3)

rap-2-h
rap-2-h

Reputation: 31948

Maybe something like :

foreach($arr as $item) {
    echo 'code: ' . $item['code'];
}

I hope it will help !

Upvotes: 0

dqw
dqw

Reputation: 1299

foreach($arr as $item) {
    echo 'code:'.$item['code'];
}

I hope this helps.

Upvotes: 0

Ben Swinburne
Ben Swinburne

Reputation: 26467

You can just cast the array as an object of type stdClass

$obj = (object) $arr

That said however, your post title seems to imply you want an object, but the post body seems like you just want to access an array key.

In which case you can just use the following. But it depends what exactly you mean by 'get all of the [code] values.'

foreach( $arr as $inner_array ) {
    $codes[] = $inner_array['code']; // Collect them all into a single dimensional array?
    echo $inner_array['code']; // Output it here?
}

Upvotes: 1

Related Questions