Removing all instances of elements from an array

I have an array that can have duplicate values

$array1 = [value19, value16, value17, value16, value16] 

I am looking for an efficient little PHP function that can take either an array or a string (depending on which simplifies it)

 $array2 = ["value1", "value16", "value17"]; or $string2 = "value1 value16 value17"; 

and removes each element in array2 or string2 from array1.

The correct conclusion for this example is:

 $array1 = [value19] 

For those who are more experienced with PHP, is something like this available in PHP?

+7
arrays php
source share
2 answers

are you looking for array_diff

 $array1 = array('19','16','17','16','16'); $array2 = array('1','16','17'); print_r(array_diff($array1,$array2)); 

Array ([0] => 19)

+10
source share

To make the string version work, use explode. Like this:

 function arraySubtract($one, $two) { // If string => convert to array $two = (is_string($two))? explode(' ',$two) : $two; $res = array(); foreach (array_diff($one, $two) as $key => $val) { array_push($res, $val); } return $res; } 

This allso returns an array with key = 0 .... n without spaces

Test with this:

 echo '<pre>'; print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7))); print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7")); print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6"))); print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6")); echo '</pre>'; 
0
source share

All Articles