Shermaine Chaingan Shermaine Chaingan - 3 months ago 20
PHP Question

array_diff() removes too many elements

I use the code below to get the difference from two arrays. But as it seems right now it removes too many elements or I'm doing something wrong.

I expect the output to be

array(333, 111)
, because the element
111
appears two times in the first array and only once in the second one. So 1x
111
should be in the output. But as of right now
111
is completely missing in the output.

Am I doing something wrong or what should I do to get this function to work as I want to?

<?php

$Inventory1 = "111,222,333,111";
$SplitInventory1 = explode(",",$Inventory1);

$Invoice = "111,222";
$SplitInvoice = explode(",",$Invoice);


$SplitResult1 = array_diff($SplitInventory1, $SplitInvoice);
echo $JointInventory1 = implode(",",$SplitResult1);

?>

Answer

HI i have used array_filter to filter the values of $SplitInventory1 array using $SplitInvoice. If array_filter's callback function return true then present value will be placed into new array.

so stpes will be

1) $var will carry the values of first array like 111,222,333,444 and using array_search it will check these exist or not in $SplitInvoicearray.

2)array_search return the key of found value so when 111 and 222 found in $SplitInvoice array then callback function will return false and these values will be not place in $diff but when 333 is searched in $SplitInvoice. this will not found in $SplitInvoice and callback function will return true and it will be placed in $diff.

3) One more thing I have unset $SplitInvoice array if a value found beacuse we need dublicate entries( due to 111 if $SplitInvoice is not unset then it will not come in $diff )

<?php
    $Inventory1 = "111,222,333,111";
    $SplitInventory1 = explode(",",$Inventory1);
    $Invoice = "111,222";
    $SplitInvoice = explode(",",$Invoice);
    $diff = array_filter($SplitInventory1, 
  function ($val) use (&$SplitInvoice) { 
    $key = array_search($val,$SplitInvoice);
    if ( $key === false ) return true;
    unset($SplitInvoice[$key]);
    return false;
  }
);

echo "<pre>";print_r($diff);

?>

Output

Array
(
    [2] => 333
    [3] => 111
)