PHP substr_count() Tutorial 🎯

beginner
8 min

PHP substr_count() Tutorial 🎯

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!

Understanding substr_count() πŸ“

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.

Syntax πŸ“

php
int substr_count(string $haystack, string $needle)
  • $haystack: The string to be searched.
  • $needle: The substring to be counted.

Practical Example πŸ’‘

Let's consider a simple example: counting the number of occurrences of the word "apple" in a string.

php
$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: 3

In 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.

Advanced Example πŸ’‘

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.

php
$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.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the PHP `substr_count()` function do?