Jump to content

sorting words :)


lopez86100

Recommended Posts

I've got something like this:

[code=php:0]
$str = $_POST['words'];
if(isset($str)){
$words = str_word_count($str, 1);
$frq = array_count_values($words);
asort($frq);

foreach ($frq as $word => $times)

if($times >= 4 && strlen($word) >= 5){
echo $word." was found ".$times." times.<br>";
}
}
[/code]

But it returns all words sorted by frequency. I want it to show only 3 repeated the most. I've tried with for loop depending of how many words is in $str but there is a problem cause it displayed even 2-3 characters words - it can't do that - it's defined in foreach loop as if (strlen($word)). Do you have any ideas ?? :)
Link to comment
https://forums.phpfreaks.com/topic/32588-sorting-words/
Share on other sites

Use a counter and only print the first three:
[code]<?php
if(isset($_POST['words'])){
    $words = str_word_count($_POST['words'], 1);
    $frq = array_count_values($words);
    asort($frq);
    $cnt = 1;
    foreach ($frq as $word => $times)
        if($cnt < 4 && strlen($word) > 4){
            echo $word." was found ".$times." times.<br>";
            $cnt++;
        }
}?>[/code]

Ken
Link to comment
https://forums.phpfreaks.com/topic/32588-sorting-words/#findComment-151581
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.