Object iteration
The PHP arrays are the most frequent collection structure used in PHP. We can squeeze pretty much anything into an array, ranging from scalar values to objects. Iterating through elements of such a structure is trivially easy using the foreach
statement. However, arrays are not the only iterable types, as objects themselves are iterable.
Let's take a look at the following array-based example:
<?php $user = [ 'name' => 'John', 'age' => 34, 'salary' => 4200.00 ]; foreach ($user as $k => $v) { echo "key: $k, value: $v" . PHP_EOL; }
Now let's take a look at the following object-based example:
<?php class User { public $name = 'John'; public $age = 34; public $salary = 4200.00; } $user = new User(); foreach ($user as $k => $v) { echo "key: $k, value: $v" . PHP_EOL; }
Executed on the console, both of these examples would yield an identical output:
key: name, value: John key: age, value: 34 key: salary, value: 4200
By default, iteration works...