Sunday, April 29, 2012

Sort and Reverse Sort Array of Strings Based on String Length in PHP

I wanted a function that would efficiently let me sort a string array by the length of each entry.  Below is a neat trick in logic that allows me to manipulate the sort function.  (1) Get the length of the string, (2) Str_pad the length with 0's, so that it is a definite length, (3) Append that number to the beginning of the string, (4) Then do rsort or sort normally.  Below is an example of an rsort implementation...

<?php

    $array_of_data = array(        "hello",
                    "php",
                    "is",
                    "awesome",
                    "1",
                    "9999",
                    "1234",
                    "12",
                    "9");
   
    print("<pre>");               
    print_r($array_of_data);
   
    /*  Output Here Is:
   
        Array
        (
            [0] => hello
            [1] => php
            [2] => is
            [3] => awesome
            [4] => 1
            [5] => 9999
            [6] => 1234
            [7] => 12
            [8] => 9
        )

    */
   
    $number_of_entries = count($array_of_data);

    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];
        $current_entry_length = strlen($current_entry);
        $appendable_entry_length = str_pad($current_entry_length, 10, "0", STR_PAD_LEFT);
        $array_of_data[$i] = $appendable_entry_length . " /|\/|\/|\ " . $array_of_data[$i];
    }
   
    rsort($array_of_data);
   
    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];

        $length_of_current_entry = strlen($current_entry);
        $array_of_data[$i] = substr($current_entry, 21, $length_of_current_entry);
    }
   
    print_r($array_of_data);
    print("</pre>");
   
    /*  Sorted Output Here Is:

        Array
        (
            [0] => awesome
            [1] => hello
            [2] => 9999
            [3] => 1234
            [4] => php
            [5] => is
            [6] => 12
            [7] => 9
            [8] => 1
        )

    */

?>

Official Function Page: http://www.php.net/manual/en/function.sort.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment