php - Counting, highlighting and printing the duplicates between two arrays -


first time posting on stackoverflow.

after printing main array, have managed highlight values found in second one, want print number of times duplicate occurs in brackets @ same time. have run out of ideas on how last part, stuck in multiple loops , other problems. paste here what's working now.

the 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 $number )  {  if ( in_array( $number, $secondary ) )   {  echo $item;  // 1 supposed highlighted, html code disappears on stackoverflow  /* number of duplicates should appear in bracket, example:   highlighted number( number of duplicates ) */   }  else  {  echo $item;  // 1 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 brackets contain number of times value found in second array, aside being colored, can't paste html code reason. sorry not making expected result more clear !

problem solved: help, first time using website, didn't expect such quick response guys. thank !

you need count values of secondary array first using array_count_values. can acquire 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 $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)


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -