How can the number of different computer models be dynamically counted and displayed in the PHP code?
To dynamically count and display the number of different computer models in PHP, you can use an associative array where the keys represent the computer models. You can then use the `count()` function to get the total number of unique models and display it. Additionally, you can loop through the array to display each unique model along with the count.
// Sample array of computer models
$computerModels = ["MacBook Pro", "Dell XPS", "Lenovo ThinkPad", "MacBook Air", "Dell Inspiron", "Lenovo Yoga", "MacBook Pro"];
// Count the number of unique computer models
$uniqueModels = count(array_unique($computerModels));
// Display the total number of unique computer models
echo "Total number of unique computer models: " . $uniqueModels . "<br>";
// Display each unique computer model along with the count
$modelCount = array_count_values($computerModels);
foreach ($modelCount as $model => $count) {
echo $model . ": " . $count . "<br>";
}
Keywords
Related Questions
- What is the correct way to access named array offsets in PHP?
- What are the potential pitfalls of querying data within loops in PHP, and how can this be avoided to improve performance?
- How can the error message "supplied argument is not a valid ODBC result" be resolved when working with ODBC connections in PHP?