DEV Community

Cover image for How to calculate keyword frequency and draw the bar chart in PHP
Yongyao Yan
Yongyao Yan

Posted on • Originally published at codebilby.com

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.";
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

$words = str_word_count($str, 1);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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().

arsort($keywords);
$keywords = array_splice($keywords, 0, 5);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

Then create a graph and set it as autoscaling.

...

For the rest of the content, please go to the link below:
https://www.codebilby.com/blog/a44-calculate-keyword-frequency-and-draw-the-bar-chart-in-php

Top comments (0)