Separate values from each array

Asked

Viewed 318 times

7

Good morning, everybody, all right? I have the code that prints the different values found in 2 arrays and these values are saved in the different variable ($different) I need to know how to print these values saved in different but stating which array it belongs to:

$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 unsuccessfully.

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

Thanks in advance.

2 answers

10

A possible solution would be to see what are common, and 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 on IDEONE.

But if it’s just the separation you want, and it’s not using the common members for anything, the simplest solution is @Gabriel Rodrigues.

  • So, but I need to take the $different variable and know what numbers are in it from their respective arrays.

  • I managed, as you said, was complicating simple thing! Thank you very much Bacco

  • 1

    Need, dispose. It is as a suggestion in the next questions you put how you will use the data. Then we may be able to help better.

  • 1

    Next time I put the code I made and the data I have, for greater understanding! Hugção

  • 1

    @Gustavofreire recommend passing the acceptance to another answer.

  • Bacco, sorry to bother you! I wonder if I can make an exe of this code, where $a would be Credit and $b would be Debito, for one to enter values in each one, then have it executed and printed in one . txt the result. Thank you

  • @Gustavofreire you can run PHP through the console, (path where php is installed)/php.exe meuscript.php

  • Good morning Bacco, rodo pelo ideone.com , what I would like to know, é uma luz de como poderia estar fazendo uma interface para usuario, onde ele entre com Valores de Credito e Valores de Debito, e o codigo php faria a comparação. Thank you for your attention

Show 4 more comments

2

It would actually be like this:

Using your Example array:

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

If you want the difference of $b in relation to the $a will:

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

Which will result in:

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

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

Now if you wish the difference of $a in relation to the $b will:

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

Which will result in:

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

Being 1.3 and 5 the difference why they do not exist in $b.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.