What is the difference between using a while loop and a foreach loop in PHP?

The main difference between a while loop and a foreach loop in PHP is in how they iterate over arrays. A while loop is a more general-purpose loop that requires manual control over the iteration process, such as incrementing a counter variable. On the other hand, a foreach loop is specifically designed for iterating over arrays and objects, automatically assigning the current array element to a variable. If you are working with arrays and want a simpler and cleaner way to iterate over them, it is recommended to use a foreach loop.

// Using a while loop to iterate over an array
$colors = array("red", "green", "blue");
$i = 0;
while($i < count($colors)){
    echo $colors[$i] . "<br>";
    $i++;
}

// Using a foreach loop to iterate over the same array
$colors = array("red", "green", "blue");
foreach($colors as $color){
    echo $color . "<br>";
}