php foreach loop example
Here's a simple PHP `foreach` loop example:
```php
// assume we have an array of names
$names = array("John", "Alice", "Bob", "Eve");
// use a foreach loop to iterate over the array and print each name
foreach ($names as $name) {
echo "$name\n";
}
```
This will output:
```
John
Alice
Bob
Eve
```
In this example:
* `$names` is an array of strings, containing four names.
* The `foreach` loop iterates over the elements of the `$names` array, assigning each element to a
variable called `$name`.
* Inside the loop, we use the `$name` variable to print out each name.
You can also use the following syntax to assign the key and value of an associative array to separate
variables:
```php
$colors = array("red" => "RRGGBB", "green" => "00FF00");
foreach ($colors as $colorName => $hexCode) {
echo "$colorName: $hexCode\n";
}
```
This will output:
```
red: RRGGBB
green: 00FF00
```
Note that in the case of an associative array, the `$colorName` variable holds the key (in this case, a
string), and the `$hexCode` variable holds the value.
You can also use the `foreach` loop to iterate over an object's properties:
```php
$person = new stdClass();
$person->name = "John";
$person->age = 30;
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
```
This will output:
```
name: John
age: 30
```