Search code examples
phpfor-loopfind-occurrences

How to find the occurrences letters of a string for given number in PHP


I have string $str = 'street'; and I want to write a function output($str, $n)

Here the $n is the count for number of occurrences in the given string. I don't want to use any PHP inbuilt functions like converting it to array first or substr_count or any other for this and want to do this just with pure for looping if it is possible

Considering $n as 2, the expected output is :-

t -> 2

e -> 2

$input = 'street';
$n = 2;

function outputs($input, $n)
{
    $input = str_replace(' ', '', $input);

    $characters = str_split($input);

    $outputs = [];

    foreach ($characters as $char)
    {
        if(!isset($outputs[$char])){
            $outputs[$char] = 1;
        } else {
            $outputs[$char] += 1;
        }
    }

    foreach ($outputs as $char => $number)
    {
        if ($number == $n) {
            echo $char . ' -> ' . $number;
            echo "\n";
        }
    }
}

outputs($input, $n);

So here, I have tried this above code and it works absolutely fine, but here I used the str_split function for this. I want to avoid its usage and need it to be done with looping only if it's possible.

I am bad at formatting questions so please spare me on this.


Solution

  • You can use a for loop instead:

    <?php
    
    $input = 'street';
    $n = 2;
    
    function outputs($input, $n)
    {
        $input = str_replace(' ', '', $input);
    
        $outputs = [];
    
        for($i = 0; $i < strlen($input); $i++)
        {
            if(!isset($outputs[$input[$i]])){
                $outputs[$input[$i]] = 1;
            } else {
                $outputs[$input[$i]] += 1;
            }
        }
    
        foreach ($outputs as $char => $number)
        {
            if ($number == $n) {
                echo $char . ' -> ' . $number;
                echo "\n";
            }
        }
    }
    
    outputs($input, $n);
    

    If you can't use strlen you can use while loop with isset:

    $i = 0;
    while(isset($input[$i])) {
        if(!isset($outputs[$input[$i]])){
            $outputs[$input[$i]] = 1;
        } else {
            $outputs[$input[$i]] += 1;
        }
        $i++;
    }