-1

I am Having Two array like the following ,

$a =array(1,2,3,4);
$b =array(1,2,5,6);

here is mycode

$c=array_diff($a,$b);
$c=array(3,4,5,6);

but i want it like the following

$c=array(3,4);

Note:

i want $a array value which is not present in $b array.

7
  • 2
    array_diff() should do exactly what you want. It works for me - codepad.viper-7.com/tMTzzG Commented Aug 8, 2013 at 6:30
  • 1
    remove $c=array(3,4,5,6);. your code already produces the results you need. In my tests the value of $c is array(3, 4) Commented Aug 8, 2013 at 6:30
  • $c=array_diff($b,$a); Commented Aug 8, 2013 at 6:31
  • 1
    @M1K1O: No. That would return all elements in $b that are not present in $a. Commented Aug 8, 2013 at 6:32
  • 2
    @SivaG Your code is correct. You are rewriting the new value. Remove $c=array(3,4,5,6); Commented Aug 8, 2013 at 6:36

4 Answers 4

7

try this

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

print_r($result);
?>

read this PHp.NET for array_diff and also refer this FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

3

i know array_diff is the best way but dianuj's answer wasnt quite kosher and a comment may not have been communicated well enough.

<?php

$a = array(1,2,3,4);
$b = array(1,2,5,6);

foreach($a as $k => $v)
{
    if (in_array($v, $b))
        unset($a[$k]);
}

var_dump($a);

Comments

2

If you want to create a new array without maintaining the old keys, try this

$c = array_values(array_diff($a, $b));

Example here - http://codepad.viper-7.com/bVaJG5

Comments

0

This should do it for you.

// get differences that in ary_1 but not in ary_2
foreach ( $ary_1 as $v1 ) {
    $flag = 0;
    foreach ( $ary_2 as $v2 ) {
        $flag |= ( $v1 == $v2 );
        if ( $flag ) break;
    }
    if ( !$flag ) array_push( $diff, $v1 );
}

where :

$ary_1 = $a & $ary_2 = $b

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.