skip to Main Content

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

Answers


  1. 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;bus;air;air";
    
    $arrayData = array_filter(explode(';', $data));
    $counts = array_count_values($arrayData);
    
    $parsedData = '';
    foreach ($counts as $key => $val) {
        $parsedData .= "$val x $key ";
    }
    
    echo $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.

    Login or Signup to reply.
  2. 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 ' ';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search