1

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?

2
  • Could you please provide a proper representation of the array? Is it an array of arrays? Please post your loop as well. Do you have troubles accessing the array? Maybe the documentation helps. Commented Nov 22, 2011 at 13:30
  • Please mention clearly what you are looking for? Commented Nov 22, 2011 at 13:31

3 Answers 3

1

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

1 Comment

If you're going to go through all the trouble of making an array and populate that contain properties of some class you have, why not just instantiate an object from the class and assign values that way? It would cut out a few steps and would be straight forward.
0

Maybe something like :

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

I hope it will help !

Comments

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

I hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.