Home > Net >  Counting occurance of an element in an array
Counting occurance of an element in an array

Time:11-30

In PHP, I'm trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each unique element, and the second containing the number of times each element occurs. For example, if the initial array was:

700,300,100,100,300,600,100,700,50

Then two new arrays would be created. The first would contain the name of each unique element:

(700,300,100,600,50)

The second would contain the number of times that element occurred in the initial array:

(2,2,3,1,1)

I've searched a lot for a solution, but nothing seems to work,Any help would be appreciated! Thanks

CodePudding user response:

You can use array_unique and array_count_values for that :

$values = [700,300,100,100,300,600,100,700,50];
  
$uniques = array_unique($values);
  
var_dump($uniques); // array(5) { [0]=> int(700) [1]=> int(300) [2]=> int(100) [5]=> int(600) [8]=> int(50) }

$counts = array_count_values($values);
  
var_dump($counts); // array(5) { [700]=> int(2) [300]=> int(2) [100]=> int(3) [600]=> int(1) [50]=> int(1) }

CodePudding user response:

<?php
    $initialArray = [700,300,100,100,300,600,100,700,50];
    $uniqueArray = array_unique($initialArray); //extracts the unique items in the array
    $frequencyArray = []; //array to hold number of times an element occur

    foreach ($uniqueArray as $number) {
        $count = array_count_values($initialArray)[$number];
        array_push($frequencyArray, $count);
    }


    print_r($uniqueArray);
    print_r($frequencyArray);
  • Related