Custom Implementation of array_intersect_assoc Without Using PHP Array Functions

The array_intersect_assoc function in PHP compares two or more arrays and returns the elements that exist in all arrays with the same keys and values. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_intersect_assoc($array1, $array2) {
    $result = [];

    // Loop through the first array
    foreach ($array1 as $key1 => $value1) {
        // Check if the key exists in the second array and the value matches
        foreach ($array2 as $key2 => $value2) {
            if ($key1 === $key2 && $value1 === $value2) {
                $result[$key1] = $value1;
                break; // Move to the next element in the outer loop
            }
        }
    }

    return $result;
}

// Example usage
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['a' => 1, 'b' => 4, 'c' => 3];

$commonElements = custom_array_intersect_assoc($array1, $array2);
print_r($commonElements);
?>

Output:

Array
(
    [a] => 1
    [c] => 3
)

Explanation:

  1. Input Parameters:
    • $array1: The first array to compare.
    • $array2: The second array to compare.
  2. Result Initialization:
    • Create an empty $result array to store matching elements with the same key and value.
  3. Outer Loop:
    • Iterate over the key-value pairs of $array1.
  4. Inner Loop:
    • For each element in $array1, iterate through $array2.
    • Compare both the key and value.
    • If both match, add the key-value pair to $result.
  5. Output:
    • Return the $result array containing elements with matching keys and values.

Keep Learning 🙂

Leave a Reply

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