Compare arrays and return the difference using PHP
Here’s how you can implement array_diff_key in PHP without using PHP’s built-in array functions. This function will compare the keys of two arrays and return the elements from the first array that are not present in the second array based on their keys.
<?php
function custom_array_diff_key($array1, $array2) {
$result = [];
// Loop through the first array
foreach ($array1 as $key => $value) {
// Check if the key does not exist in the second array
if (!isset($array2[$key])) {
$result[$key] = $value;
}
}
return $result;
}
// Example usage
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 20, 'd' => 30];
$difference = custom_array_diff_key($array1, $array2);
print_r($difference);
?>
Output:
Array
(
[a] => 1
[c] => 3
)
Explanation:
- Input: Two arrays, $array1 and $array2.
- Iteration: Loop through $array1 using foreach.
- Key Comparison: Check if the key in $array1 does not exist in $array2 using isset.
- Result Construction: Add the key-value pairs from $array1 that are not in $array2 to the $result array.
- Output: The $result array contains the differences by key.
Keep Learning 🙂