107

How can I loop through all the properties of object?. Right now I have to write a new code line to print each property of object

echo $obj->name;
echo $obj->age;

Can I loop through all the properties of an object using foreach loop or any loop?

Something like this

foreach ($obj as $property => $value)  
Daric
  • 15,251
  • 11
  • 40
  • 57

6 Answers6

163

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}
David Harkness
  • 34,910
  • 10
  • 110
  • 128
  • 11
    "Object of class stdClass could not be converted to string" could well be a resulting error if the object is not an array. – landed Jul 22 '16 at 12:03
  • print_r($obj); can also help. Prints given object's fields recursively. – fandasson Aug 04 '17 at 18:48
10

For testing purposes I use the following:

//return assoc array when called from outside the class it will only contain public properties and values 
var_dump(get_object_vars($obj)); 
Dimi
  • 209
  • 3
  • 4
3

Before you run the $object through a foreach loop you have to convert it to an array:

$array = (array) $object;  

 foreach($array as $key=>$val){
      echo "$key: $val";
      echo "<br>";
 }
Rex
  • 301
  • 2
  • 3
2

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}
Budove
  • 277
  • 2
  • 7
  • 19
  • 4
    This only works if the object implements `\ArrayAccess` or is an `array`, otherwise the following is thrown: `FATAL ERROR Uncaught Error: Cannot use object of type SomeType as array` – NoodleOfDeath Nov 02 '18 at 16:46
2

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

JG Estiot
  • 885
  • 1
  • 10
  • 8
0

David's answer is solid as long as either: a) you only need access to public attributes, or b) you are working with the stdClass object. If you have defined private or protected attributes in a class and want to display all attributes, simply add an instance method that iterates the properties:

class MyClass {

  public $public_attr1;
  private $private_attr2;
  protected $protected_attr3;

  function iterateAttributes() {
    foreach ($this as $attr=>$value) {
      echo "$attr: $value <br/>";
    }
  }

}
GraceRg
  • 23
  • 4