note 107088 deleted from function.sort by danbrown

From: Date: Fri, 06 Jan 2012 19:06:11 +0000
Subject: note 107088 deleted from function.sort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185396@lists.php.net to get a copy of this message
Note Submitter: holdoffhunger at gmail dot com ---- The string-length sort-code posted by jazzduck is a very slim, efficient alternative to mine. However, if several strings in the array are the same size, they won't be sorted at all, whereas it would be nice if they were sorted alphabetically. Adding one if-else statement and this extra strcmp in there solves the problem: <?php $array_of_data = array( "hello1", "hello2", "hello8", "hello4", "hello7", "hello9", "hello5", "hello3", "hello6"); print("<pre> Before\n\n"); print_r($array_of_data); function cmp( $x, $y ) { if((strlen( $x ) - strlen( $y )) != 0) { return (strlen( $x ) - strlen( $y )); } else { return(strcmp($x, $y)); } } usort($array_of_data, cmp); print("\n After\n\n"); print_r($array_of_data); print("</pre>"); ?>

« previous php.notes (#185396) next »