How to calculate keyword frequency and draw the bar chart in PHP

How to calculate keyword frequency and draw the bar chart in PHP

This post shows you how to calculate the keyword frequency from text and draw the bar chart by using the JpGraph library.

Calculate the keyword frequency

Suppose we have a string like this:

$str = "There are two cats on the table. One on the left side is eating an apple, the other on the right side is eating a fish.";

It is easy to calculate the keyword frequency by using the PHP built-in functions.

First, we convert all text to lowercase.

$str = strtolower($str);

Then, we can extract all words from text by using the function str_word_count().

$words = str_word_count($str, 1);

By setting the second parameter's value to be 1, the function str_word_count() returns an array $words with all the words in the string $str. After that, use the function array_count_values() to count all the valules inside the array $words. Actually, it gets the frequency of all the words in the array $words and returns as an array $keywords.

$keywords = array_count_values($words);

If we just want the top 5 keywords, use the function arsort() to sort the array $keywords from highest to lowest and get the first 5 elements by using the function array_splice().

$keywords = array_splice($keywords, 0, 5);

Finally, calculate the percentage of each keyword like this:

$total = count($words);

$frequency = [];
foreach ($keywords as $key => $value) {
    $frequency[$key] = number_format(($value / $total) * 100, 2);

Draw the keyword frequency bar chart

In this example, we use the graph creating library, JpGraph, to draw the keyword frequency bar chart. First, copy the library files under the root path of your website and include the JpGraph files:

require_once ('jpgraph-4.4.1/src/jpgraph.php');
require_once ('jpgraph-4.4.1/src/jpgraph_bar.php');

Then create a graph and set it as autoscaling.


For the rest of the content, please go to the link below:

Did you find this article valuable?

Support Yongyao Yan by becoming a sponsor. Any amount is appreciated!