1

i have got a mysql database with words. I am printing all the words with a while statement. So i get like:

potato tomato lettace

This is all working fine, but i want to sort the words by length. I have tried:

if(strlen($go['words']) == 4 ){ echo "this are the 4 letter words:"; }

but this will print the sentence before every 4 letter word. Whereas, I want it to be printed only 1 time as a header for all 4 letter words. Of course i want to do this also for 5,6,7 letter words.

I have thought about making multiple sql query's but thats too much for the server to handle with a lot of visitors.

rahulmishra
  • 611
  • 1
  • 11
  • 27
Gilio53
  • 13
  • 3
  • 1
    If you don't want to give your query an order by clause then have a look at http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php – VMai Aug 16 '14 at 17:55
  • http://stackoverflow.com/questions/838227/php-sort-an-array-by-the-length-of-its-values – rahulmishra Aug 16 '14 at 17:57
  • I am using the order by clause to order by length. But the question here is to give them headers like: 4 letter words:, 5 letter words: – Gilio53 Aug 16 '14 at 18:02

2 Answers2

1

you can use a temporary variable like this:

$tempLen = 0;
while(...)
{
    if(strlen($go['words']) == 1 && $tempLen < 1){ 
        echo "this are the 1 letter words:"; 
        $tempLen = 1;
    }
    ...
    if(strlen($go['words']) == 4 && $tempLen < 4){ 
        echo "this are the 4 letter words:"; 
        $tempLen = 4;
    }
    ...
}
0

Is this what you want?

$words = array("fish", "mouse", "rabbit", "turtle", "duck");
sort($words);
$last_letter_count = 0;

foreach($words as $word)
{
    if ( strlen($word) != $last_letter_count )
    {
        $last_letter_count = strlen($word);
        echo "These are the $last_letter_count letter words:\n";
    }

    echo $word . "\n";
}

output:

These are the 4 letter words:
duck
fish
These are the 5 letter words:
mouse
These are the 6 letter words:
rabbit
turtle
beardedlinuxgeek
  • 1,604
  • 15
  • 23