<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array_diff($arr1,$arr2); foreach($arr3 as $element) echo "$element, "; //1, 3, 5, 7, 9, ?>
It can also take a 3rd array parameter. It returns all the elements in the 1st array but not in the 2nd and 3rd array.
<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array(1,3); $arr=array_diff($arr1,$arr2,arr3); foreach($arr as $element) echo "$element, "; //5, 7, 9, ?>
Similarly, more arrays can be taken, all elements in the 1st array as well as in the other arrays will be deleted.
<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr=array_diff($arr1,$arr2,array(1,3),array(5)); foreach($arr as $element) echo "$element, "; //7, 9, ?>
It can also take associative arrays, both the keys and values will be compared.
<?PHP $arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99); $arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99); $arr = array_diff($arr1,$arr2); print_r($arr); //the result is: Array ( [apple] => 2.2 [nuts] => 4.99 [meat] => 6.99 ) ?>
<?PHP $arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99); $arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99); $arr = array_diff_key($arr1,$arr2); print_r($arr); //the result is: Array ( [nuts] => 4.99 [meat] => 6.99 ) ?>
array_intersect() function returns the shared elements of the 1st array and other arrays.
<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array_intersect($arr1,$arr2); foreach($arr3 as $element) echo "$element, "; //2, 4, 6, 8, ?>