Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of array merge in PHP

Tags:

php

Ok, two arrays:

$first = array(1,2,3,4,5,6,7,8,9,10);
$second = array(1,2,3,4,5);

Is there a way (without looping through them if it can be helped) of doing an array_merge style function where it returns this array:

$new = array(6,7,8,9,10);

Where if it finds a match, it does not return it.

like image 633
benhowdle89 Avatar asked Jun 08 '12 15:06

benhowdle89


2 Answers

See array_diff()

$new = array_diff($first, $second);
print_r($new);

/*
Array
(
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
*/
like image 145
flowfree Avatar answered Sep 18 '22 18:09

flowfree


array_diff() should do this:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Array
(
    [1] => blue
)
like image 25
John Conde Avatar answered Sep 19 '22 18:09

John Conde