Comparing values ​​from two PHP arrays

I have two arrays with objects in it. I want to compare each property of an 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 correct. Iterating over arrays and then comparing is the right approach?

Object properties:

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

      

All parameters are strings.

+3


source to share


2 answers


You shouldn't use for (expr1; expr2; expr3)

arrays to iterate; better to use foreach (array_expression as $value)

Also, you are comparing every element of array1 to every element of array2, but if there is a match, you compare it 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 in array_uintersect

orarray_walk

+3


source


  • In if

    one bracket is placed correctly, that is probably the main problem and makes unexpected results.
  • levenstein

    is not a trivial operation, you shouldn't do it twice, just to compare it, it is better to store the result in a variable.
  • Without more information about input and expected output, it is impossible to help you more.

Here's the code fixed.



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

      

0


source







All Articles