PHP Program to Estimate the Time Taken to Read an Article

In many articles in blogs we see the estimated time it will take to read the article.

This is useful in that it helps the reader to decide whether to read the article in spot or save it for later or whether to read the article at all!

You too can add the functionality to your articles through this code snippet. Mind you it is written for PHP based programs only!

Here’s an example program in PHP that calculates the time required to read an article based on the average reading speed –

<?php

// Define the article as a string
$article = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et nibh ac augue mattis faucibus. Duis tincidunt ex libero, quis congue justo sagittis eget. Donec nec leo eu purus tristique rhoncus.";

// Define the average reading speed in words per minute
$reading_speed = 200;

// Calculate the number of words in the article
$word_count = str_word_count($article);

// Calculate the time required to read the article in minutes
$reading_time = ceil($word_count / $reading_speed);

// Output the result
echo "It will take approximately " . $reading_time . " minutes to read this article.";

?>

The $article here can come from a database or any other source. Adjust the code accordingly.

In this example, the program first defines the article as a string and the average reading speed in words per minute as a constant value.

Next, the program uses the str_word_count() function to count the number of words in the $article string. The function returns the number of words as an integer value, which is stored in the $word_count variable.

Then, the program calculates the time required to read the article in minutes by dividing the word count by the reading speed and rounding up to the nearest minute using the ceil() function. The result is stored in the $reading_time variable.

Finally, the program outputs the result by concatenating a string with the $reading_time variable using the concatenation operator ‘.‘. The output will display the estimated time required to read the article in minutes.

Php