Custom Implementation of array_intersect Without Using PHP Array Functions

The array_intersect function in PHP returns the common values from two or more arrays. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

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

    // Loop through the first array
    foreach ($array1 as $value1) {
        // Check if the value exists in the second array
        foreach ($array2 as $value2) {
            if ($value1 === $value2) {
                $result[] = $value1;
                break; // Stop checking further for this value
            }
        }
    }

    return $result;
}

// Example usage
$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];

$commonValues = custom_array_intersect($array1, $array2);
print_r($commonValues);

Output:

Array
(
    [0] => 3
    [1] => 4
    [2] => 5
)

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 the common values.
  3. Outer Loop:
    • Iterate through the values of $array1.
  4. Inner Loop:
    • For each value in $array1, check if it exists in $array2.
    • If a match is found, add the value to the $result array and break the inner loop to avoid duplicate entries.
  5. Output:
    • Return the $result array containing values present in both input arrays.

Keep Learning 🙂

Leave a Reply

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