Sort words by length

Discussion in 'PHP' started by emitind, Dec 29, 2008.

  1. #1
    Is there a way to order the following words by length?

    Thanks.
     
    emitind, Dec 29, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    jestep, Dec 29, 2008 IP
  3. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #3
    You can put them into an array using the following:
    
    $string = 'Bannana
    Apple
    Orange
    Pear
    Pea';
    
    $array = explode("\n", $string);
    ?>
    
    PHP:
     
    crazyryan, Dec 29, 2008 IP
  4. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #4
    <?php
    
    $string = 'Banana
    Apple
    Orange
    Pear
    Pea';
    
    $array = explode("\n", $string); /* Split it up */
    usort($array, create_function('$a, $b', 'return strlen($a)-strlen($b);')); /* Largest -> smallest */
    $string = implode("\n", $array); /* Put it back together again */
    
    echo $string;
    /* Output */
    PHP:
     
    Danltn, Dec 29, 2008 IP
  5. emitind

    emitind Peon

    Messages:
    567
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks for the replies, I've managed it using:

    			function cmp( $a, $b ) {
    				return strlen($a)-strlen($b) ;
    			}
    			
    			
                            $string = "pear
                                          bannana
                                          pea";	
    			$a = explode("\n", $string);
    			usort($a, "cmp");
    			
    			foreach ($a as $key => $value) {
    			
    				
                            echo "$value<br />";
    
    				
    			}
    PHP:
     
    emitind, Dec 29, 2008 IP
  6. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #6
    Just a FYI
    usort($array, create_function('$a, $b', 'return strlen($a)-strlen($b);'));
    PHP:
    does exactly the same as all of
    function cmp( $a, $b ) {
                    return strlen($a)-strlen($b) ;
                }
                
                usort($a, "cmp");
    PHP:
     
    Danltn, Dec 29, 2008 IP