0

I am trying to "subtract" the values of an array in php. I used array_diff but it doesn't seem to work for more than one value.

<?php

    $array1 = array(1,3,7,10,7);
    $array2 = array(1,7);

    $result=array_diff($array1,$array2);
    print_r($result);

?>

//Output//
Array ( [1] => 3 [3] => 10 )

What I would like to do is return 3,7,10 instead of excluding all 7's. Thanks in advance!

3
  • Do you want to remove only the first instance in the array or is this array exactly the array you want to remove elements from? Commented Feb 15, 2014 at 23:44
  • It's unclear what you're asking. Are you wanting to remove one copy of each item in $array2? Commented Feb 15, 2014 at 23:44
  • you want the function to substract the last found element ? Commented Feb 15, 2014 at 23:49

2 Answers 2

1

Try:

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);

foreach( $removals as $remove ) {
    foreach( $array1 as $key => $value ) {
        if ($value === $remove ) {
            unset($array1[ $key ]);
            break;
        }
    }
}

print_r($array1); // Array ( [1] => 3 [3] => 10 [4] => 7 )
sort($array1)
print_r($array1); // Array ( [0] => 3 [1] => 7 [2] => 10 )
Sign up to request clarification or add additional context in comments.

6 Comments

this returns Array ( [1] => 3 [2] => 7 [3] => 10 [4] => 7 ) doesnt it ?
Array ( [1] => 3 [3] => 10 [4] => 7 )
do you want it reversed?
QUOTE => What I would like to do is return 3,7,10
@Dwza Just sort() it.
|
0

based on thelastshadows post but shorter and may faster because only one foreach

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);
foreach( $removals as $remove ) {
    unset($array1[array_search($remove,$array1)]);
}
sort($array1);
print_r($array1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.