How to Use str_word_count() Function in PHP 8.2 With Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `str_word_count()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP 8.2, the `str_word_count()` function is used to count the number of words in a string. It provides several options to customize its behavior. Below is an example demonstrating the usage of `str_word_count()`:

<?php

// Example string
$string = "Hello, how are you today?";
// Count the number of words in the string
$wordCount = str_word_count($string);
echo "Total words in the string: $wordCount\n";

// Count the number of words and return an array containing all the words
$wordsArray = str_word_count($string, 1);
echo "Array of words:\n";
print_r($wordsArray);

// Count the number of words and return an array where the key is the position of the word in the string
$wordsPosition = str_word_count($string, 2);
echo "Array with word positions:\n";
print_r($wordsPosition);

// Count the number of words and return an array containing the positions and lengths of the words
$wordsDetails = str_word_count($string, 3);
echo "Array with word details:\n";
print_r($wordsDetails);

?>

Output:

Total words in the string: 5
Array of words:
Array
(
[0] => Hello
[1] => how
[2] => are
[3] => you
[4] => today
)
Array with word positions:
Array
(
[0] => 0
[1] => 6
[2] => 10
[3] => 14
[4] => 18
)
Array with word details:
Array
(
[0] => Array
(
[0] => 0
[1] => 5
)
[1] => Array
(
[0] => 6
[1] => 3
)
[2] => Array
(
[0] => 10
[1] => 3
)
[3] => Array
(
[0] => 14
[1] => 3
)
[4] => Array
(
[0] => 18
[1] => 5
)
)

This example demonstrates how to use `str_word_count()` to count words in a string and retrieve additional information such as an array of words, their positions, and their lengths.