Is there a more efficient way to count the occurrences of a specific character in a string than using substr_count?

Using substr_count to count the occurrences of a specific character in a string can be inefficient for large strings or when counting multiple characters. One more efficient way to count occurrences is by using a loop to iterate through each character in the string and incrementing a counter variable when the specific character is found.

function countOccurrences($string, $char) {
    $count = 0;
    for ($i = 0; $i < strlen($string); $i++) {
        if ($string[$i] === $char) {
            $count++;
        }
    }
    return $count;
}

$string = "hello world";
$char = "l";
echo countOccurrences($string, $char); // Output: 3