What is the purpose of the for loop in the PHP code snippet?
The purpose of the for loop in the PHP code snippet is to iterate over an array and output each element with an added comma at the end, except for the last element which should not have a comma. This is a common task when formatting arrays for display purposes. To solve this issue, we can modify the for loop to check if it is the last element before adding a comma.
// Original code snippet with issue
$array = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($array); $i++) {
echo $array[$i] . ",";
}
// Fixed code snippet
$array = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($array); $i++) {
echo $array[$i];
if ($i < count($array) - 1) {
echo ",";
}
}