What are some alternative methods for counting specific characters in a string in PHP besides using array functions?

When counting specific characters in a string in PHP without using array functions, one alternative method is to loop through each character in the string and compare it to the specific character we are counting. We can then increment a counter variable each time a match is found. Another approach is to use regular expressions to match the specific character and then count the number of matches found in the string.

// Method 1: Loop through each character in the string
$string = "hello world";
$charToCount = 'o';
$count = 0;

for ($i = 0; $i < strlen($string); $i++) {
    if ($string[$i] == $charToCount) {
        $count++;
    }
}

echo "Number of '$charToCount' in the string: $count\n";

// Method 2: Using regular expressions
$string = "hello world";
$charToCount = 'o';
$count = preg_match_all("/$charToCount/", $string);

echo "Number of '$charToCount' in the string: $count\n";