What is the best way to compare two arrays in PHP and filter out common elements?

To compare two arrays in PHP and filter out common elements, you can use the array_diff() function. This function compares two arrays and returns the values from the first array that are not present in the second array. By using array_diff() on the two arrays, you can easily filter out the common elements and get the unique values from each array.

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

$unique_array1 = array_diff($array1, $array2);
$unique_array2 = array_diff($array2, $array1);

print_r($unique_array1);
print_r($unique_array2);