Looping array using each() and foreach() loop
Looping array using each() and foreach() loop
In PHP, you can loop through an array using `foreach()` and `each()` loops. Here's how you can use both:
### Using `foreach()` Loop:
The `foreach()` loop is a convenient way to iterate over arrays. Here's an example:
```php
<?php
// Sample array
$colors = array("Red", "Green", "Blue", "Yellow");
// Loop through the array using foreach
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
```
In this example, `foreach($colors as $color)` iterates through each element in the `$colors` array and assigns the current element's value to the variable `$color`. It then echoes each color followed by a line break.
### Using `each()` Function:
The `each()` function returns the current key-value pair from an array and advances the array cursor. Here's an example of using `each()`:
```php
<?php
// Sample array
$colors = array("Red", "Green", "Blue", "Yellow");
// Reset the array pointer
reset($colors);
// Loop through the array using each() function
while ($element = each($colors)) {
echo "Key: " . $element['key'] . ", Value: " . $element['value'] . "<br>";
}
?>
```
In this example, the `each()` function is used within a `while` loop. It returns an array with 'key' and 'value' indices for the current element. The `reset($colors)` function is used to ensure that the array pointer is at the beginning of the array before using `each()`.
Both methods achieve similar results, but `foreach()` is more commonly used for iterating through arrays in PHP due to its simplicity and readability.
Comments
Post a Comment