[Solved] Count elements with a the same name in an array in php


array_count_values

array_count_values() returns an array using the values of array as keys and their frequency in array as values.

$varArray = array(); // take a one empty array

foreach ($rowa as $rowsa)
{
    $sql = "SELECT count(*) as NUMBER FROM BANDZENDINGEN WHERE FB_AFGESLOTEN = 'F' AND FB_AKTIEF = 'T' AND FI_AFVOERKANAAL = 1 AND FI_RAYONID = $rowsa  AND FI_VERRIJKINGID < 1;";
    $sfh = $dbh->prepare($sql);
    $sfh->execute();
    $row = $sfh->fetchAll(PDO::FETCH_COLUMN, 0);

    array_push($row, $rows['FC_RAYON']);
    //print_r($row);
    //array_push($varArray,$rows['FC_RAYON']); // Also May I think $rows['FC_RAYON'] is give value like RT-SCB-PB01,ASDC-PBSN etc.
    array_push($varArray,$row[1]); // I have push the send value of array like RT-SCB-PB01,ASDC-PBSN etc. and make in single array.
}

$dupArrays = array_count_values($varArray); // It will return Counts all the values of an array
echo 'Total No Items: '.count($dupArrays).'<br><br>';
echo "<pre>";
print_r($dupArrays);
echo "</pre>";

The output will be :

Total No Items: 3

Array
(
    [RT-SCB-PB01] => 3 // Count of duplicate value of RT-SCB-PB01 is 3
    [ASDC-PBSN] => 4 // Count of duplicate value of ASDC-PBSN is 3
    [ASDW-PBSN] => 1 // Count of duplicate value of ASDW-PBSN is 3
)

Get using foreach method

foreach($dupArrays as $key => $value){
    echo $key.' Count '.$value.' times.';
    echo "<br>";
}

Output:

RT-SCB-PB01 Count 3 times.
ASDC-PBSN Count 4 times.
ASDW-PBSN Count 1 times.

6

solved Count elements with a the same name in an array in php