note 107045 deleted from function.sort by googleguy

From: Date: Tue, 24 Jul 2012 04:00:22 +0000
Subject: note 107045 deleted from function.sort by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189379@lists.php.net to get a copy of this message
Note Submitter: holdoffhunger at gmail dot com ---- 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 rsort implementation... <?php // Released Under Affero General Public License, Version 3 (AGPL3) // Author: holdoffhunger@gmail.com $array_of_data = array( "hello", "php", "is", "awesome", "1", "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] => 1234 [6] => 12 [7] => 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]; $current_entry_explosion = explode(" /|\/|\/|\ ", $current_entry); $array_of_data[$i] = $current_entry_explosion[1]; } print_r($array_of_data); print("</pre>"); /* Sorted Output Here Is: Array ( [0] => awesome [1] => hello [2] => 1234 [3] => php [4] => is [5] => 12 [6] => 9 [7] => 1 ) */ ?>

« previous php.notes (#189379) next »