Foxx
Foxx

Reputation: 15

How do you compare two arrays to get the truth when one element of these arrays is different

I have two arrays that only distinguish one element, I would like to get the truth even if one element is different. A different element can be in different indexes, in my example it is in the 3rd index of the array.

  $aRoutesByClass = array (
               1 => 'odbiorca',
               2 => 'umowy-z-odbiorcami',
               3 => '{agreement2lvl:id}',
               4 => 'wydarzenia',
                      )


   $aUserSettingUrl = array (
               1 => 'odbiorca',
               2 => 'umowy-z-odbiorcami',
               3 => '13732',
               4 => 'wydarzenia',
                           )


           if ($aRoutesByClass == $aUserSettingUrl) {
                    //FALSE
                    //I wish it were true if only one element is different
                }

I hope I described my problem clearly.

Upvotes: 0

Views: 72

Answers (3)

Foxx
Foxx

Reputation: 15

There are cases where the tables are actually equal. Example: $aRoutesByClass = array ( 1 => 'zmiany-w-windykacji', ) $aUserSettingUrl = array ( 1 => 'zmiany-w-windykacji', )

Upvotes: 0

Osah Prince
Osah Prince

Reputation: 73

If i understand what you means, you want to compare two arrays and if only one element is different it should show true.

<?php
$aRoutesByClass = array (
               1 => 'odbiorca',
               2 => 'umowy-z-odbiorcami',
               3 => '{agreement2lvl:id}',
               4 => 'wydarzenia',
                      );


   $aUserSettingUrl = array (
               1 => 'odbiorca',
               2 => 'umowy-z-odbiorcami',
               3 => '13732',
               4 => 'wydarzenia',
                           );
$counter = 0;

for($i = 1; $i<= count($aRoutesByClass); $i++){
    if($aRoutesByClass[$i] != $aUserSettingUrl[$i]){
        $counter++;
    }
}

if($counter == 1){
    echo "Even";
}else{
    echo "Odd";
}
?>

Upvotes: 0

Forge Web Design
Forge Web Design

Reputation: 835

You can use array_diff() to compare two array, it will give result of array of different elements then you can check count() is 1 then you will get true try the following code

$aRoutesByClass = array (
       1 => 'odbiorca',
       2 => 'umowy-z-odbiorcami',
       3 => '{agreement2lvl:id}',
       4 => 'wydarzenia',
    );


    $aUserSettingUrl = array (
            1 => 'odbiorca',
            2 => 'umowy-z-odbiorcami',
            3 => '13732',
            4 => 'wydarzenia',
    );

    $result = array_diff($aRoutesByClass,$aUserSettingUrl); 

    if (count($result) == 1) {
        echo "true";exit;
    }

Upvotes: 2

Related Questions