note 107088 added to function.sort

From: Date: Thu, 05 Jan 2012 23:07:02 +0000
Subject: note 107088 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-185383@lists.php.net to get a copy of this message
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>"); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 68.0.209.235 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/107088 Del: integrated -- https://master.php.net/note/delete/107088/integrated Del: useless -- https://master.php.net/note/delete/107088/useless Del: bad code -- https://master.php.net/note/delete/107088/bad+code Del: spam -- https://master.php.net/note/delete/107088/spam Del: non-english -- https://master.php.net/note/delete/107088/non-english Del: in docs -- https://master.php.net/note/delete/107088/in+docs Del: other reasons-- https://master.php.net/note/delete/107088 Reject -- https://master.php.net/note/reject/107088 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185383) next »