note 111883 added to function.usort

From: Date: Mon, 08 Apr 2013 22:30:22 +0000
Subject: note 111883 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-194395@lists.php.net to get a copy of this message
As the documentation says, the comparison function needs to return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1. <?php usort($array, function($a, $b) { if($a->integer_property > $b->integer_property) { return 1; } elseif($a->integer_property < $b->integer_property) { return -1; } else { return 0; } }); ?> can be simplified to <?php usort($array, function($a, $b) { return $a->integer_property - $b->integer_property; }); ?> This of course applies to any comparison function that calculates an integer "score" for each of its arguments to decide which is "greater". ---- Server IP: 69.147.83.199 Probable Submitter: 202.175.135.150 ---- Manual Page -- http://php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/111883 Del: integrated -- https://master.php.net/note/delete/111883/integrated Del: useless -- https://master.php.net/note/delete/111883/useless Del: bad code -- https://master.php.net/note/delete/111883/bad+code Del: spam -- https://master.php.net/note/delete/111883/spam Del: non-english -- https://master.php.net/note/delete/111883/non-english Del: in docs -- https://master.php.net/note/delete/111883/in+docs Del: other reasons-- https://master.php.net/note/delete/111883 Reject -- https://master.php.net/note/reject/111883 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194395) next »