skip to Main Content

So I have two arrays of objects in PHP (each object contains name and email). What am I looking for is the fastest way to get for each element of the first array, all the elements from the second array that have a similar name or email (I am using the similar_text function to achieve this).

The way I am doing it now is with two foreach functions comparing every element of the first array to every element of the second array (and doing some customization of the results, but that is not really important). Is there any better way to achieve this? Because for a large number of elements it can take a very long time.

I am using PHP 7.3.12, so a solution that can be done with this version is appreciated.

Thank you!

Edit: Here is the base code without all the customization I was talking about:

$data = [];

foreach($project_developers as $pd1) {
    $name1 = $pd1->name;
    $email1 = strstr($pd1->email, '@', true);

    foreach($project_developers as $pd2) {
        //Make sure it's not the same developer db entry.
        if($pd1->id != $pd2->id) {
            $name2 = $pd2->name;
            similar_text($name1, $name2, $percent_name);
            
            $email2 = strstr($pd2->email, '@', true);

            similar_text($email1, $email2, $percent_email);

            //If the similarity is greater than 80% we can save it.
            if($percent_name > 80 || $percent_email > 80) {
                if(empty($data[$pd2->id][$pd1->id])) {
                    $data[$pd1->id][$pd2->id] = $pd2;
                }
            }
        }
    }
}

2

Answers


  1. array_intersect($array1,$array2);
    

    Which will return your expected result.

    Login or Signup to reply.
  2. array_intersect

    You can use "array_intersect()". It returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

    Try This,

        $a = ['name' => 'Randy', 'email' => '[email protected]'];
        $b = ['name' => 'Rhoads', 'email' => '[email protected]'];
        
        print_r(array_intersect_key($a, $b));
    

    Output :

        Array([email] => [email protected])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search