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 some best practices for handling login systems in PHP, especially when using MySQL and sessions?
- What potential pitfalls should be considered when working with PHP scripts that handle user inputs and data storage?
- How can PHP developers adapt their code to account for changes in browser behavior, such as the User-Agent being deprecated for security reasons?