PHP - Count Unique Word and Add Counted Prefix

66 Views Asked by At

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..

2

There are 2 best solutions below

7
AmooAti On BEST ANSWER

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.

0
Wimanicesir On

Your code worked! However you did something weird to display it.

If we use the simplest way to show it you can see it works:

<?php
$data = "air;air;air;bus;air;air;bus;air;air";

$a = substr_count($data,"air");
$b = substr_count($data,"bus");

echo $a . ' x ' . 'air' . ' ' . $b . ' x ' . 'bus';

However this can be more dynamic:

<?php
$data = "air;air;air;bus;air;air;bus;air;air";

$words = array_unique(explode(';', $data));

foreach ($words as $word) {
    echo substr_count($data, $word) . ' x ' .$word;
    echo ' ';
}