Problem Statement:
Write a PHP function to count the number of words in a string.
Solution Explanation:
- We use PHP’s built-in function
str_word_count()to count words in a string.
PHP Code:
<?php
function countWords($str) {
return str_word_count($str);
}
// Test cases
echo countWords("Hello world!"); // Output: 2
echo countWords("PHP is a great language!"); // Output: 5
?>