How to iterate object properties in PHP

You can loop over all the public properties in an object using a foreach loop, like this:

class Dog {
  public $name = 'Good dog';
  public $age = 10;
  public $color = 'gray';
}

$dog = new Dog();

foreach ($dog as $key => $value) {
  echo $key . ': ' . $value . '<br>';
}

Download my free PHP Handbook!