How to Manually Implement array_udiff_assoc in PHP Without Built-in Functions

The array_udiff_assoc function in PHP compares the values and keys of two arrays using a custom callback function and returns the differences. Below is a manual implementation of this functionality without using any built-in functions.

<?php
// Function to replicate array_udiff_assoc
function manualArrayUdiffAssoc($array1, $array2, $callback) {
    $result = []; // Initialize an empty result array

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

        foreach ($array2 as $key2 => $value2) {
            // Compare both keys and values using the callback
            if ($key1 === $key2 && $callback($value1, $value2) === 0) {
                $isUnique = false;
                break;
            }
        }

        // Add to result if unique
        if ($isUnique) {
            $result[$key1] = $value1;
        }
    }

    return $result; // Return the resulting array
}

// Example usage
$array1 = ["a" => 10, "b" => 20, "c" => 30];
$array2 = ["a" => 10, "b" => 25, "d" => 40];

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

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

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

Output:

The difference with keys is: Array
(
    [b] => 20
    [c] => 30
)

Explanation:

  1. Input Arrays: Two associative arrays are passed along with a callback function.
  2. Key-Value Comparison: Each key-value pair in $array1 is compared with $array2. Both the key and value must match for exclusion.
  3. Custom Logic: The callback function allows flexible comparison logic.
  4. Result: The resulting array contains key-value pairs unique to $array1.

Keep Learning 🙂

Leave a Reply

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