Search code examples
phparraysstring-comparisonarray-difference

PHP array_diff for comparing 2 arrays with different length?


I used array_diff to compare to 2 strings converted into arrays by explode, it can compare 2 arrays of the same length, how I accomplish comparing arrays of different length?

Ex.
Array1: The quisck browsn fosx
Array2: The quick brown fox
Works!!

Array1: The quisck browsn
Array2: The quick brown fox
Doesn't Work!!(fox was not mentioned)

<?php
$str1 = "The quisck browsn";
$str2 = "The quick brown fox";
$tempArr;
$var2;
$ctr=0;

echo "Array1:<br> $str1 <br><br>Array2:<br> $str2";

$strarr = (explode(" ",$str1));
echo("<br>");

$strarr2 = (explode(" ",$str2));
echo("<br>");

$result = array_diff($strarr,$strarr2);
//print_r($result);

if (count($result) > 0){
    echo "<br>Differences: | " ;
    foreach ($result AS $result){
        echo $result." | ";
    }
 }

Solution

  • Try this

    $str1 = "The quisck browsn";
    $str2 = "The quick brown fox";
    $tempArr;
    $var2;
    $ctr=0;
    
    $strarr = (explode(" ",$str1));
    echo("<br>");
    
    $strarr2 = (explode(" ",$str2));
    echo("<br>");
    
    if(sizeof($strarr) > sizeof($strarr2)){
        $result = array_diff($strarr,$strarr2);
    }else{
        $result = array_diff($strarr2,$strarr);
    }
    

    The above will return the difference between array size greater than the lower.i.e. element present in first array but not in 2nd.

    But if you want the complete difference between 2 of them i.e. element in first array does not exist in 2nd and vice versa you can do something as

    $fullDiff = array_merge(array_diff($strarr, $strarr2), array_diff($strarr2, $strarr));