how to loop trough object keys in php
In PHP, you can loop through an object's properties using the
`foreach` loop:
```php
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 30;
$obj->city = 'New York';
foreach ($obj as $key => $value) {
echo "$key: $value\n";
}
```
This will output:
```
name: John
age: 30
city: New York
```
The `$key` variable holds the property name (e.g. `name`,
`age`, etc.), and the `$value` variable holds the corresponding
value.
You can also use the `get_object_vars()` function to get an
array of object properties, and then loop through it:
```php
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 30;
$obj->city = 'New York';
foreach (get_object_vars($obj) as $key => $value) {
echo "$key: $value\n";
}
```
This will produce the same output as the previous example.
Note that if you want to loop through an object's properties in
a specific order, you can use the `uasort()` function to sort
the properties by key:
```php
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 30;
$obj->city = 'New York';
uasort($obj, function($a, $b) {
return strcmp(key($a), key($b));
});
foreach ($obj as $key => $value) {
echo "$key: $value\n";
}
```
This will output the properties in alphabetical order by key.
Alternatively, you can use a `foreach` loop with the
`object_get()` function to get an array of object properties:
```php
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 30;
$obj->city = 'New York';
foreach (array_keys(get_object_vars($obj)) as $key) {
echo "$key: " . object_get($obj, $key) . "\n";
}
```
This will produce the same output as the previous examples.