Hello i am trying to count number of related word from a list of words that are separated with comma. In short i am try to work with tags and i want to get the first word and count it similar words. For example:
$words = 'php, codes, php, script, php, chat.';
In the above example the word PHP appears three time any possibly way to catch them in sperate form to out put this:
- php – 3
- codes – 1
- script – 1
Mean while i was able to loop out the words from my db and separate each of them as a link but i also want to use them as tag references to count each tags words found.
Advertisement
Answer
Here is one way that works with PHP 7.2+:
<?php $words = rtrim('php, codes, php, script, php, chat.',"."); $exploded = explode(", ",$words); $arrCount = array_count_values($exploded); var_dump($arrCount);
live code: https://3v4l.org/BNXjf
The code trims off the period punctuating the string. Then it explodes the string into the array $exploded using a 2-character string composed of a comma followed by a space character. Then the code defly uses the PHP 7 function array_count_values which creates a new array in this case $arrCount and this array’s keys are the values of $exploded and its values are the number of times each value appears in $exploded as the var_dump() of $arrCount reveals.