Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to group elements of an array based on their first occurrence in PHP

1 Answer

0 votes
function group_elements($arr) {
    $frequency = array_fill(0, 10, 0);
   
    for ($i = 0; $i < count($arr); $i++) {
        $frequency[$arr[$i]]++;
        echo "frequency[arr[" . $i . "]] = " . $frequency[$arr[$i]] . " arr[" . $i . "] = " . $arr[$i] . "\n";
    }
   
    for ($i = 0; $i < count($arr); $i++) {
        if ($frequency[$arr[$i]] != 0) {
            $total_frequency = $frequency[$arr[$i]];
            while ($total_frequency--) {
               echo $arr[$i] . " ";
            }
            $frequency[$arr[$i]] = 0;
        }
    }
}
 
$arr = array(8, 3, 7, 8, 2, 5, 8, 5, 1, 9, 8, 1, 7);
  
group_elements($arr);
 
 
  
  
/*
run:
  
frequency[arr[0]] = 1 arr[0] = 8
frequency[arr[1]] = 1 arr[1] = 3
frequency[arr[2]] = 1 arr[2] = 7
frequency[arr[3]] = 2 arr[3] = 8
frequency[arr[4]] = 1 arr[4] = 2
frequency[arr[5]] = 1 arr[5] = 5
frequency[arr[6]] = 3 arr[6] = 8
frequency[arr[7]] = 2 arr[7] = 5
frequency[arr[8]] = 1 arr[8] = 1
frequency[arr[9]] = 1 arr[9] = 9
frequency[arr[10]] = 4 arr[10] = 8
frequency[arr[11]] = 2 arr[11] = 1
frequency[arr[12]] = 2 arr[12] = 7
8 8 8 8 3 7 7 2 5 5 1 1 9 
  
*/

 



answered Aug 14, 2022 by avibootz
...