Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting, highlighting and printing the duplicates between two arrays

Tags:

arrays

php

First time posting on stackoverflow.

After printing the main array, I have managed to highlight the values that are found in the second one, but I also want to print the number of times that the duplicate occurs in brackets at the same time. I have run out of the ideas on how to do that last part, I get stuck in multiple loops and other problems. I will paste here what's working for 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 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 that the value is found in the second array, aside from being colored, but I can't paste the html code for some reason. Sorry for not making the expected result more clear !

PROBLEM SOLVED: Thanks to everyone for your help, first time using this website, didn't expect such a quick response from you guys. Thank you very much !

like image 230
Lost in Code Avatar asked Oct 31 '22 04:10

Lost in Code


1 Answers

You need to get the count values of your secondary array first using array_count_values. This is what you 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 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)

like image 193
Narendrasingh Sisodia Avatar answered Nov 13 '22 16:11

Narendrasingh Sisodia