array_diff_assoc in php without using array function

To implement a function similar to PHP’s array_diff_assoc without using any built-in array functions, you can manually compare both the keys and values of two arrays. Here’s how it can be done:

<?php

function customArrayDiffAssoc($array1, $array2) {
    $difference = []; // Initialize an empty array to store differences.

    foreach ($array1 as $key => $value) {
        // Check if the key exists in the second array and if the value matches.
        if (!isset($array2[$key]) || $array2[$key] !== $value) {
            $difference[$key] = $value; // Add the differing key-value pair to the result.
        }
    }

    return $difference;
}

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

// Output the result
print_r($result);
?>

Output:

Array
(
    [b] => 2
    [c] => 3
)

Explanation:

  1. Initialize an Empty Array: Create an empty array $difference to store the key-value pairs that are different.
  2. Iterate Over the First Array: Use a foreach loop to go through each key-value pair in $array1.
  3. Check Key and Value: For each key-value pair in $array1:
    • If the key does not exist in $array2 or the value corresponding to the key in $array2 is different, consider it a difference.
  4. Add to Result: Add the differing key-value pair to the $difference array.
  5. Return the Difference Array: After the loop, return the $difference array

Keep Learning:)

Leave a Reply

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