How can PHP arrays be efficiently compared in a foreach loop to avoid redundant output?

When comparing PHP arrays in a foreach loop, it is important to avoid redundant output by checking if the current value exists in the second array before outputting it. This can be achieved by using the in_array() function to check if the value exists in the second array before outputting it. This ensures that each value is only output once, even if it appears multiple times in the arrays being compared.

$array1 = [1, 2, 3, 4];
$array2 = [2, 3, 4, 5];

foreach ($array1 as $value) {
    if (!in_array($value, $array2)) {
        echo $value . " ";
    }
}