Manual Implementation of array_udiff Without Using Built-in Functions

The array_udiff function in PHP compares values of two or more arrays using a custom callback function and returns the differences. Here’s how to manually replicate its behavior without using the built-in array_udiff function.

<?php
// Function to find the difference between arrays using a custom comparison function
function manualArrayUdiff($array1, $array2, $callback) {
    $result = []; // Initialize an empty array for the result

    foreach ($array1 as $value1) {
        $isUnique = true;

        foreach ($array2 as $value2) {
            // Use the callback function to compare values
            if ($callback($value1, $value2) === 0) {
                $isUnique = false;
                break;
            }
        }

        // If the value is unique, add it to the result
        if ($isUnique) {
            $result[] = $value1;
        }
    }

    return $result; // Return the resulting array
}

// Example usage
$array1 = [10, 20, 30, 40];
$array2 = [30, 40, 50, 60];

// Custom comparison function
$callback = function($a, $b) {
    return $a <=> $b; // Standard three-way comparison
};

$result = manualArrayUdiff($array1, $array2, $callback);

echo "The difference is: ";
print_r($result);
?>

Output:

The difference is: Array
(
    [0] => 10
    [1] => 20
)

Explanation:

  1. Input Arrays: Two arrays are passed along with a callback function.
  2. Custom Comparison: Each value in $array1 is compared with every value in $array2 using the callback function.
  3. Store Unique Values: Values unique to $array1 are added to the result.
  4. Output: The result contains the differences as calculated by the custom logic.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *