note 84860 deleted from function.abs by hholzgra
| From: | hholzgra@php.net | Date: | Sun, 15 Apr 2012 19:30:15 +0000 |
| Subject: | note 84860 deleted from function.abs by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-187150@lists.php.net to get a copy of this message | ||
Note Submitter: lkj dot korn at gmail dot com
----
[EDIT by danbrown AT php DOT net: Merged two posts by the same author.]
This is a note to concordia's comment at http://us.php.net/manual/en/function.abs.php#58508
I believe there is an easier way to turn a positive number into a negative one and vice versa in one
line:
<?php
function change_pol($integer){
return (0 - $integer);
}
?>
It takes another additional line to check if it's really a number:
<?php
function change_pol($integer){
if(!is_numeric($integer)){ return false; }
return (0 - $integer);
}
?>
Keep in mind that if I do 0 - -5 (given that $integer is -5), it will turn into +, thus turning the
result into +5. Works like a charm for me. Input like '-5' will work as well (as PHP turns
strings automatically into an integer or float), even '-.9' will return as 0.9.
Another thing I'd like to note is that the variable name $integer used in my examples
aren't really advised as the function goes beyond simple integers. Initially, I used this
function only for the handling of integers, hence the variable name. It is only later that I've
discovered it goes beyond integers. 0 will also return to 0 (if that shouldn't be obvious).
Perhaps it is better to make it return NULL instead of FALSE when it fails the is_numeric condition,
so that there's no mix with the function's result to be false instead of actually 0,
however only checking with '===' instead of '==' should solve this, I believe.