Count, select and print duplicates between two arrays

First time posting on stackoverflow.

After printing the main array, I managed to highlight the values ​​found in the second, but I also want to print the number of times when the duplicate occurs in brackets at the same time. I have run out of ideas on how to do this last part, I am stuck in several cycles and other problems. I will put here what works now.

Code:

$main = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ); $secondary = array( 1, 6, 10, 6, 17, 6, 17, 20 ); foreach ( $main as $number ) { if ( in_array( $number, $secondary ) ) { echo $item; // this one is supposed to be highlighted, but the html code disappears on stackoverflow /* this is where the number of duplicates should appear in bracket, example: highlighted number( number of duplicates ) */ } else { echo $item; // this one is simple } } 

EXPECTED RESULT:

1 (1), 2, 3, 4, 5, 6 (3), 7, 8, 9, 10 (1), 11, 12, 13, 14, 15, 16, 17 (2), 18, 19, 20 (1)

Basically, the brackets contain the number of times this value is found in the second array, except for the color, but for some reason I can’t insert the html code. Sorry for not making the expected result more understandable!

SOLVING THE PROBLEM: Thank you all for your help, using this site for the first time, I did not expect such a quick response from you guys. Thank you very much!

+6
source share
3 answers

First you need to get the count values ​​of your secondary array using array_count_values. This is something you can purchase as

 $main = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); $secondary = array(1, 6, 10, 6, 17, 6, 17, 20); $count_values = array_count_values($secondary); foreach ($main as $key => $value) { if (in_array($value, $secondary)) { echo $value . "<strong>(" . $count_values[$value] . ")</strong>"; echo ( ++$key == count($main)) ? '' : ','; } else { echo $value; echo ( ++$key == count($main)) ? '' : ','; } } 

Output:

1 (1), 2,3,4,5,6 (3), 7,8,9,10 (1), 11,12,13,14,15,16,17 (2), 18, 19, 20 (1)

+2
source

Assuming $ secondary is the one that has tricksters, you should go this route in a different way:

 $dupes = array(); foreach($secondary as $number) { if (in_array($number, $main)) { $dupes[$number]++; } } var_dump($dupes); 
0
source
  <?php $main = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17,18,19,20); $secondary = array( 1, 6, 10, 6, 17, 6, 17, 20 ); $result =array(); foreach($main as $key => $value){ $i=0; foreach($secondary as $key1 => $value1){ if($value == $value1){ $i++; } $result[$value] = $i; } } $resultString =''; foreach($result as $key => $value){ $resultString .=$key.'('.$value.'),' ; } echo trim($resultString,','); ?> 

Result:

 1(1),2(0),3(0),4(0),5(0),6(3),7(0),8(0),9(0),10(1),11(0),12(0),13(0),14(0),15(0),16(0),17(2),18(0),19(0),20(1) 
0
source

Source: https://habr.com/ru/post/987283/


All Articles