0

When I print_r($a); the output like this:

Array
(
    [0] => stdClass Object
        (
            [tid] => 3
            [vid] => 1
            [name] => cPanel
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [1] => stdClass Object
        (
            [tid] => 4
            [vid] => 1
            [name] => whm
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [2] => stdClass Object
        (
            [tid] => 5
            [vid] => 1
            [name] => test
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

)

the array key maybe increment. now, i want to output all the name' s value of the array. when i used the following code. it shows me an error.

foreach($a as $a->name){
    echo a->name;
}
2
  • 2
    Please always point out what error you are getting exactly. Commented May 26, 2011 at 13:40
  • Funny how this type of questions gets a bunch of answers practically before the posters submit has refreshed. Lol! :o) Commented May 26, 2011 at 13:43

6 Answers 6

3

Try this:

foreach($a as $value){
   echo $value->name;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Do this:

foreach($a as $object){
    echo $object->name;
}

Then read this: http://php.net/manual/en/control-structures.foreach.php

Doing:

foreach ($array as $key => $value) {
    echo "Array key: $key   Value: $value";
}

Will print out each value in an array and the name of the key.

Comments

2

Using -> is for objects; => is for arrays


foreach($a as $key => $value){
    echo $key . " " . $value;
}

1 Comment

True, but this is not what he wants to achieve (look at the sample data)
1

The array contains a number of objects, but the foreach loop will work exactly the same way as for normal variables. The correct syntax is

foreach ($a as $object)
 echo $object->name;

Comments

0

The typical foreach syntax used a key => value pair.

foreach ($a as $key => $value)
{
 var_dump($value);
}

Comments

0

This is the answer:

foreach($a as $value)
echo $value['name'];

1 Comment

The key contains an object, though technically one could I suppose maybe do this: foreach($a as (array) $value){ echo $value['name'];} but I don't see the use and probably less efficient.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.