What is the difference between using a for loop and a foreach loop to access elements of an array in PHP?

When accessing elements of an array in PHP, the main difference between using a for loop and a foreach loop is the syntax and convenience. A for loop requires you to manually specify the array index and iterate through each element, while a foreach loop automatically iterates over each element of the array without needing to specify the index. The foreach loop is often preferred for its simplicity and readability when working with arrays in PHP.

// Using a for loop to access elements of an array
$array = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($array); $i++) {
    echo $array[$i] . " ";
}

// Using a foreach loop to access elements of an array
$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
    echo $value . " ";
}