How can PHP be used to calculate and display an average star rating based on user inputs?
To calculate and display an average star rating based on user inputs in PHP, you can store the user ratings in an array, calculate the average rating by summing up all ratings and dividing by the total number of ratings, and then display the average rating on the webpage.
<?php
// User ratings array
$userRatings = [4, 5, 3, 2, 5];
// Calculate average rating
$totalRatings = count($userRatings);
$sumRatings = array_sum($userRatings);
$averageRating = $sumRatings / $totalRatings;
// Display average rating
echo "Average Rating: " . round($averageRating, 1) . " stars";
?>
Keywords
Related Questions
- What are the potential pitfalls of not using PHP tags in a PHP file?
- Is using try/catch a viable option to handle the "Corrupt EXIF header" error in PHP?
- What are the potential pitfalls of using ezpdf for generating PDFs with PHP, and are there alternative libraries or methods that may be more compatible with browsers like MS-IE?