Welcome to our comprehensive guide on the PHP substr_count() function! This function is a powerful tool for counting the number of occurrences of a substring within a string. Let's dive right in!
The substr_count() function in PHP returns the number of times a substring is found within a string. It's handy when you need to count instances of a specific pattern in your code.
int substr_count(string $haystack, string $needle)$haystack: The string to be searched.$needle: The substring to be counted.Let's consider a simple example: counting the number of occurrences of the word "apple" in a string.
$text = "I have 3 apples and 2 oranges.";
$count = substr_count($text, "apple");
echo "The count of 'apple' is: " . $count; // Output: The count of 'apple' is: 3In this example, we have a string containing "apple" three times. When we use substr_count(), it returns the number of times "apple" appears within the string.
Let's take a more complex example to demonstrate the versatility of substr_count(). Suppose we have a list of fruits, and we want to count the number of occurrences of each fruit.
$fruits = "Apples, Oranges, Bananas, Apples, Grapes, Apples, Oranges";
$fruit_array = explode(",", $fruits);
$fruit_count = array_count_values($fruit_array);
print_r($fruit_count);In this example, we first convert our string of fruits into an array using the explode() function. Then, we use the array_count_values() function to count the occurrences of each fruit in the array.
What does the PHP `substr_count()` function do?