Google News
logo
PHP Program to Loop through the values of a PHP object
In the following example of PHP program to loop through the values of a PHP object :
Program :
<?php
// Define a class
class Person {
    public $name;
    public $age;
    public $gender;

    public function __construct($name, $age, $gender) {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
}

// Create an object of the class
$person = new Person('John', 30, 'Male');

// Loop through the values of the object
foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}
?>
Output :
name: John
age: 30
gender: Male
In this example, we defined a class `Person` with three properties `name`, `age`, and `gender`, and a constructor to initialize the values of the properties.

Then, we created an object of the class `Person` with values 'John', 30, and 'Male' for the properties.

Finally, we looped through the object using a `foreach` loop and printed out the key-value pairs of the object using the `$key` and `$value` variables.