How to Implement array_uintersect in PHP Without Built-in Functions

The array_uintersect function in PHP compares the values of two or more arrays using a custom callback function and returns the common values. Below is a manual implementation without using PHP’s built-in function.

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

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

    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 = manualArrayUintersect($array1, $array2, $callback);

echo "The intersection of the arrays is: ";
print_r($result);
?>

Output:

The intersection of the arrays is: Array
(
    [0] => 30
    [1] => 40
)

Explanation:

  1. Input Arrays: Two arrays are passed along with a custom comparison callback.
  2. Value Comparison: Each value in $array1 is compared with every value in $array2 using the callback function.
  3. Add Common Values: If the comparison returns 0 (indicating equality), the value is added to the result array.
  4. Result: The resulting array contains the common values between the two arrays

Keep Learning 🙂

Leave a Reply

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