Cuberonix Cuberonix - 2 months ago 11
PHP Question

Creating function to count characters in a string

I'm trying to create a function to count the occurrences of a letter within a string. Here is what I have so far:

<?php
function charCount ($str, $char){
for($i=0;$i <= strlen($str);$i++){
if($str[$i] == $char){
echo $char;
}
}
}
?>

<?php
$string = charCount ("This is a test", "t");
echo "$string";
?>


The output should just be a number.

Answer

Try this:

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

In the for loop must count to the length of the string minus 1, so it is used:
$i < strlen($str);