简体   繁体   中英

php - Most frequent element in array?

This is the function:

function mostFrequent($x) {
    $counted = array_count_values($x);
    arsort($counted);
    return(key($counted));    
}

This is the call in the

tag:

<?php
    $x=mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
    echo "$x";
?>

This should work right? Also, how do I avoid having to use the temp $x for the echo and just echo the result of the function call directly?

Your solution seems reasonable.

<?php
    echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
?>
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));     

however, it seems wrong way and using a "temp" variable would be better.
Eventually you will learn that it is better to separate business logic from presentation logic.
So, the business of your business logic turns out to be exactly collecting these "temp" variables for the later use in the presentation logic.

also note that variables in PHP require no quotes to address. you are confusing them with strings.

echo $x;

is the proper syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM