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.
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);
<?php
function charCount ($str, $char){
$count = 0;
for($i=0;$i <= strlen($str);$i++){
if($str[$i] == $char){
++$count;
}
}
return $count;
}
?>
<?php
$str = "This is a test";
$char = "t";
$string = charCount($str, $char);
echo $string;
// Another way to do this
$number = substr_count($str, $char);
echo $number;
?>
The simplest solution would be to use the in-build PHP function substr_count
Note: For case insensitive search, convert $text to lower case and then apply function
$text = "This is a test";
$search = "t";
echo substr_count(strtolower($text), $search); // Case insensitive search. Prints 3.
echo substr_count($text, $search); // Case sensitive search. Prints 2.