-4

I have two arrays: array1=(1,2,3,4) and array2=(1,2,5,6)

I need to create array3 which contain only those value which lie in array2 not in array1. So my array3 will be array3(5,6).

Albzi
  • 15,431
  • 6
  • 46
  • 63
  • So, do you have any code that tries to do that? Otherwise, it'll be difficult to help you out. – Alfabravo Jan 30 '15 at 12:35
  • Have you looked at [array_diff()](http://www.php.net/manual/en/function.array-diff.php) at all? The PHP manual is there for a reason.... telling us what we can do with PHP, and how to do it! – Mark Baker Jan 30 '15 at 12:36
  • Possible duplicate of: http://stackoverflow.com/questions/8691329/php-how-to-compare-two-arrays-and-remove-duplicate-values – AgeDeO Jan 30 '15 at 12:36
  • Didn't know SO now does people's work. Sorry about the rant but sometimes, people go too far to get some rep. – Alfabravo Jan 30 '15 at 13:06

4 Answers4

1

try using array_diff() like this:

<?php
$array1=array(1,2,3,4);
$array2=array(1,2,5,6);

print_r(array_diff($array2,$array1));// to reinitialize key use array_values().
?>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
0

You need the function array_diff() http://php.net/array_diff

$a1 = array(0 => "a", 1 => "b", 2 => "c");
$a2 = array(3 => "c", 4 => "b", 5 => "d");
print_r(array_diff($a1,$a2));
//Array (
//  [0] => a
//)
Phate01
  • 2,499
  • 2
  • 30
  • 55
0

You can do it the below way

$array1=array (1,2,3,4);
$array2=array (1,2,5,6);
$result = array_diff ( $array1 , $array2);
echo "<pre>";print_r($result);exit;

This will output

Array
(
    [2] => 3
    [3] => 4
)

If you want to reindex array you can use below code

array_values($result);

Output:

Array
    (
        [0] => 3
        [1] => 4
    )
Veerendra
  • 2,562
  • 2
  • 22
  • 39
0

This is the solution:

<?php

$a = array(0=> 1, 1 => 23, 2 => 3);
$b = array(0=> 1, 1 => 23, 2 => 3, 3=> 5, 4=> 10);
$c = array_diff($b, $a);
var_dump($c);
?>

Output:

array (size=2)
  3 => int 5
  4 => int 10
Abel
  • 538
  • 5
  • 8
  • 28