Monday, January 7, 2013

PHP: Remove intersect element(s) in array

$array1 = array('abc', 'efg', 'hij', 'klm', 'nop', 'qrs');
$array2 = array('tuv', 'abc', 'wxyz', 'qrs', 'hij');


// Find intersection
$intersection = array_intersect($array1, $array2); 

echo '<pre>'.print_r($intersection, true).'</pre>';
/* output: 
Array
(
    [0] => abc
    [2] => hij
    [5] => qrs
)
*/

// Extract
if(!empty($intersection)){

   foreach ($intersection as $key => $value) {
      unset($$array1[$key]);
   }

}

echo '<pre>'.print_r($array1, true).'</pre>';
/* output: 
Array
(
    [1] => efg
    [3] => klm
    [4] => nop
)
*/

Refer site:
Unset - http://sg2.php.net/manual/en/function.unset.php
Array intersect - http://php.net/manual/en/function.array-intersect.php

2 comments: