What is the difference between using a for loop and a foreach loop when working with arrays in PHP?

When working with arrays in PHP, the main difference between using a for loop and a foreach loop is the way you iterate over the array elements. A for loop allows you to specify the start and end points of the iteration, while a foreach loop automatically iterates over each element in the array without the need to specify the index. If you need to access both the index and value of each element in the array, a for loop may be more suitable. However, if you only need to access the values of the array elements, a foreach loop is more convenient.

// Example using a for loop to iterate over an array
$colors = array("red", "green", "blue");
$length = count($colors);

for($i = 0; $i < $length; $i++) {
    echo $colors[$i] . "<br>";
}

// Example using a foreach loop to iterate over an array
$colors = array("red", "green", "blue");

foreach($colors as $color) {
    echo $color . "<br>";
}