Separate values from each array

7

Good day, people, okay? I have the code that prints the different values found in 2 arrays and those values get stored in the different variable ($ different) I need to know how I can print these values stored in different but telling which array it belongs:

$a = [1,2,3,4,5];
$b = [2,4,6,7];
$diferentes = 1, 3, 5, 7

I need to print:

$a = 1,3,5
$b = 7

I tried to use array_diff but failed.

$diff1 = array_diff($diferentes, $a); 
$diff2 = array_diff($diferentes, $b);

Thank you in advance.

    
asked by anonymous 05.04.2016 / 14:28

2 answers

9

One possible solution would be to see which ones are common, and to extract from the rest:

$a = [1,2,3,4,5];
$b = [2,4,6,7];

$common = array_intersect( $b, $a ); 

$diff1 = array_diff( $a, $common );
$diff2 = array_diff( $b, $common );

See working at IDEONE .

But if it's just the separation you want, and you're not going to use the common members for anything, the simplest solution is @Gabriel Rodrigues.

    
05.04.2016 / 14:44
2

In reality it would look like this:

Using your Example array:

$a = [1,2,3,4,5];
$b = [2,4,6,7];

If you want the $b difference from $a will do:

$diff1 = array_diff($b, $a);

That will result in:

array (size=2)
  2 => int 6
  3 => int 7

Being 6 and 7 the difference because they do not exist in $a .

Now if you want the difference of $a compared to $b will do:

$diff2 = array_diff($a,$b);

That will result in:

array (size=3)
  0 => int 1
  2 => int 3
  4 => int 5

Being 1,3 and 5 the difference because they do not exist in $b .

    
05.04.2016 / 15:32