How can PHP foreach loops be optimized to prevent duplicate output of elements in an array?

When using a foreach loop in PHP to iterate over an array, duplicate output of elements can occur if the array contains duplicate values. To prevent this, you can use the array_unique() function to remove duplicates from the array before looping through it. This ensures that each element is only output once.

$originalArray = [1, 2, 2, 3, 4, 4, 5];
$uniqueArray = array_unique($originalArray);

foreach ($uniqueArray as $element) {
    echo $element . "<br>";
}