Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare values from two Arrays PHP

I have two Arrays with Objects in it. I want to compare each property of the array with each other.

function compare ($array1, $array2)
{
        $uniqueArray = array();
        for ($i = 0; $i < count($array1); $i++)
        {
            for ($j = 0; $j < count($array2); $j++)
            {
                if(levenshtein($array1[$i]->getCompany(), $array2[$j]-     >getCompany() > 0 || levenshtein($array1[$i]->getCompany(), $array2[$j]->getCompany()) < 3))
                {
                    //add values to $unqiueArray    
                }
            }
        }
        print_r($uniqueArray);
}

I'm not sure if my code is right. The iteration over the arrays and then the compare is that the right approach?

Object Properties:

private $_company;
private $_firstname;
private $_sirname;
private $_street;
private $_streetnumber;
private $_plz;
private $_place;

All prperties are strings.

like image 235
mk2015 Avatar asked Jun 15 '26 11:06

mk2015


1 Answers

You shouldn't use for (expr1; expr2; expr3) for iterating arrays; it's better to use foreach (array_expression as $value) Also, you are comparing every element on array1 with every element on array2, but if there's a match you compare them again later. Try something like this

foreach($array1 as $k1 => $v1) {
    foreach($array2 as $k2 => $v2) {
        if(your_condition()) {
            $uniqueArray[] = $v1;
            unset($array2[$k2])
        }
    }
}

Or maybe do some research on array_uintersect or array_walk

like image 90
Voro Avatar answered Jun 18 '26 02:06

Voro