How to find the index of Nth occurrence of a character in a string with PHP

1 Answer

0 votes
function GetNthIndexOfCh($s, $ch, $n) {
    $count = 0;
    
    for ($i = 0; $i <= strlen($s) - 1; $i++) {
        if ($s[$i] == $ch) {
            $count += 1;
            if ($count == $n) {
                return $i;
            }
        }
    }
    
    return -1;
}
        
$str = "java php python c# javascript";

echo GetNthIndexOfCh($str, 'a', 3);



/*
run:

20

*/

 



answered Mar 28, 2024 by avibootz
...