LOKESH LOKESH - 3 months ago 7
PHP Question

how to find difference in single dimensional array with single dimensional array in php

I have two array two array. First is multidimensional and other is single dimensional. I want to find difference between them. How do I found.

$arrayresult

Array 1

Array (
[0] => Array ( [0] => ishani.lad [1] => 9033187384 )
[1] => Array ( [0] => rajkumar.prajapati [1] => 8460078459 )
[2] => Array ( [0] => lokesh.bhandari [1] => 9687060900 )
[3] => Array ( [0] => shishanshu.rai [1] => 8401915337 )
[4] => Array ( [0] => vishal.dake [1] => 9879815299 )
[5] => Array ( [0] => mohsin [1] => 8347163123 )
)


$useduser

Array 2

Array (
[0] => ishani.lad
[1] => rajkumar.prajapati
[2] => lokesh.bhandari
)


I need difference as result as below
Result

Array (
[0] => Array ( [0] => shishanshu.rai [1] => 8401915337 )
[1] => Array ( [0] => vishal.dake [1] => 9879815299 )
[2] => Array ( [0] => mohsin [1] => 8347163123 )
)


I have used solution as

$resultremainig = [];
foreach($arrayresult as $val2){
if(!in_array($val2[0], $useduser)){
echo $val2[0]."<br>";
$resultremainig[] = $val2;
}
}


But it show last record also. Result of above code is as below. It always show me last record in second array's also

Array (
[0] => Array ( [0] => lokesh.bhandari [1] => 9687060900 )
[1] => Array ( [0] => shishanshu.rai [1] => 8401915337 )
[2] => Array ( [0] => vishal.dake [1] => 9879815299 )
[3] => Array ( [0] => mohsin [1] => 8347163123 )
)

Answer

If you wanted you could try using nested loops like so:

<?php

    $arrOne = $arrFinal = [
        ["ishani.lad",         9033187384],
        ["rajkumar.prajapati", 8460078459],
        ["lokesh.bhandari"   , 9687060900],
        ["shishanshu.rai"    , 8401915337],
        ["vishal.dake"       , 9879815299],
        ["mohsin"            , 8347163123],
    ];

    $arrTwo = [
        "ishani.lad",
        "rajkumar.prajapati",
        "lokesh.bhandari",
    ];

    foreach($arrOne as $key=>$item){
        foreach($arrTwo as $k=>$v){
            if(in_array($v, $item)){
                unset($arrFinal[$key]);
            }
        }
    }

    var_dump($arrFinal);

    // PRODUCES:::
    array (size=3)
      3 => 
        array (size=2)
          0 => string 'shishanshu.rai' (length=14)
          1 => int 8401915337
      4 => 
        array (size=2)
          0 => string 'vishal.dake' (length=11)
          1 => int 9879815299
      5 => 
        array (size=2)
          0 => string 'mohsin' (length=6)
          1 => int 8347163123
Comments