|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2002-09-26 13:52 UTC] bill at softky dot com
The wonderful math-function list is missing a very important and simple function: sign(). The is the comlpementof abs(), and together with abs() allows you to separate the magnitude and sign of a number, e.g. for graphing purposes (it's hard to graph a negative number of pixels, and displaying money as "$-99" looks dumb). It's a one-line function, so I've already written my own, but it really ought to be built-in. Thanks! PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 07:00:01 2025 UTC |
Quick search showed that there is no well know scripting language that has such function. C++/C# has this but they are not scripting languages. The following code does the same. Also we have to think about BC(backward compatibility) with older scripts. function sign($x){ return (int)((abs($x)-$x)? -1:$x>0); } Thank you for you suggestion.Patrick, adding a new library function _absolutely_ breaks BC. For example: <?php function abs($x) { return 3; } // Output: Fatal error: Cannot redeclare abs() ?> Do you want every script that declares a function `sign` to suddenly not work any more? How would this *not* be a compatibility issue?sign is very usefull in usort function exemple : <?php $people = [ ["name"=>"John","age"=>20], ["name"=>"Jack","age"=>30], ["name"=>"Paul","age"=>25], ] usort($people,function($a, $b){ return sign($a['age'] - $b['age']); }); ?>For usort() this is not needed. function($a,$b) { return $a['age'] - $b['age']; } is fine.