Doug Cassidy
Doug Cassidy

Reputation: 1905

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 of $array1, from $array2.

so, What I want is:

1.99
2.99

Ive tried array_diff(), which will take out both of the 1.99 and leave me with only 2.99.

Upvotes: 4

Views: 62

Answers (3)

Doug Cassidy
Doug Cassidy

Reputation: 1905

I did similar to @iainn:

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

Upvotes: 0

Farsheel
Farsheel

Reputation: 610

First merge the two arrays the find unique elements .Try array_merge() and array_unique()

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

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

?>

Upvotes: 0

iainn
iainn

Reputation: 17417

You can take advantage of the fact array_search will only return one matching element from the target array, and use it to remove that 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 $array1 can contain elements that aren't present in $array2 then you'll need to add a check that the result of array_search is not false.

Upvotes: 4

Related Questions