Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_diff() removes too many elements

Tags:

arrays

php

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 1x111 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);

?>
like image 314
Shermaine Chaingan Avatar asked Mar 09 '26 13:03

Shermaine Chaingan


1 Answers

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
)
like image 61
Passionate Coder Avatar answered Mar 11 '26 02:03

Passionate Coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!