Remove only one matching element from two arrays

$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);

I want to remove only one matching element from $ array1, from $ array2.

So I want:

1.99
2.99

Ive tried array_diff()that will get both out 1.99and leave me only with 2.99.

+4
source share
3 answers

You can take advantage of the fact that it array_searchreturns only one corresponding element from the target array and use it to remove from $array2:

$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);

foreach ($array1 as $remove) {
  unset($array2[array_search($remove, $array2)]);
}

If it $array1may contain elements that are not present in $array2, then you need to add a check that the result is array_searchnot false.

+4
source

First merge the two arrays, find the unique elements .Try array_merge()andarray_unique()

<?php
$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);

print_r(array_unique(array_merge($array1, $array2)));

?>
0
source

I look like @iainn:

foreach($array1 as $k=>$v){
    if(in_array($v, $array2)){
        unset($array1[$k]);
        break;  
    }
}
0
source

Source: https://habr.com/ru/post/1688697/


All Articles