phpcountuniqueprefiximplode

PHP - Count Unique Word and Add Counted Prefix


I tried this

$data = "air;air;air;bus;air;air;bus;air;air";
$a = substr_count($data,"air");
$b = substr_count($data,"bus");
$data = implode($a . ' x ', array_unique(explode('air;', $data)));
echo $data;

And I get

7 x bus;7 x air

What I actually want to get is

7 x air 2 x bus

Help please..


Solution

  • You can use explode function to make an array from the string and then use array_count_values which returns an array with the count of all the values.

    <?php
    $data = "air;air;air;bus;air;air;air;air";
    
    $arrayData = explode(';', $data);
    $counts = array_count_values($arrayData);
    
    $parsedData = '';
    foreach ($counts as $key => $val) {
        $parsedData .= $val > 1 ? "$val x $key, " : "$key, ";
    }
    
    echo rtrim($parsedData, ', ');
    

    Note: array_count_values is case-sensitive and if you want to count the values with case-insensitive, first you need to make the whole string upper case or lower case using strtoupper orstrtolower.