How can PHP functions like array_unique and in_array be utilized to filter out duplicate values in an array efficiently?
To filter out duplicate values in an array efficiently, we can use PHP functions like array_unique and in_array. First, we can use array_unique to remove duplicate values from the array, then we can use in_array to check if a value already exists in the array before adding it. This combination ensures that only unique values are present in the array.
// Original array with duplicate values
$array = [1, 2, 2, 3, 4, 4, 5];
// Filter out duplicate values
$unique_array = array_unique($array);
// Initialize an empty array to store unique values
$filtered_array = [];
// Iterate through the unique array and check if each value is already present
foreach ($unique_array as $value) {
if (!in_array($value, $filtered_array)) {
$filtered_array[] = $value;
}
}
// Output the filtered array
print_r($filtered_array);