How to Create a Custom PHP Function for Comparing Array Keys Without Built-In Functions
The array_intersect_key function in PHP compares the keys of two or more arrays and returns the elements from the first array whose keys exist in the other arrays. Below is a custom implementation of this functionality without using PHP’s built-in array functions.
Code Example:
<?php
function custom_array_intersect_key($array1, $array2) {
$result = [];
// Loop through the first array
foreach ($array1 as $key1 => $value1) {
// Check if the key exists in the second array
foreach ($array2 as $key2 => $value2) {
if ($key1 === $key2) {
$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' => 10, 'c' => 30, 'd' => 40];
$commonKeys = custom_array_intersect_key($array1, $array2);
print_r($commonKeys);
?>
Output:
Array
(
[a] => 1
[c] => 3
)
Explanation:
- Input Parameters:
- $array1: The first array to compare.
- $array2: The second array to compare.
- Result Initialization:
- Create an empty $result array to store elements with matching keys.
- Outer Loop:
- Iterate over the keys and values of $array1.
- Inner Loop:
- For each key in $array1, iterate through $array2 to check if the key exists.
- If the keys match, add the key-value pair from $array1 to $result.
- Output:
- Return the $result array containing elements with matching keys.
Keep Learning 🙂