# The opposite of abs()

A gem from the comments on the (otherwise pretty good) PHP manual on the abs() function:

Sometimes you may want to do the opposite of abs(): turn a positive number into a negative.<?php

function turn_neg ($num) { return $num - $num * 2; }

?> But this can create errors when you put a negative number inside...

turn_neg (-2) returns 6.

<?php

turn_neg (-2); // 6.

?> The solution is to make another function to determine if the number is negative or not.

<?php

function is_neg ($num) { return $num < 0; }

function turn_neg ($num) { if (is_neg ($num)) { return $num - $num * 2; } else { return abs ($num); } }

turn_neg (2); // -2 turn_neg (-2); // 2

?> Or, if the number is not negative, you could also return false.

Although this is a clear demonstration of little reflection on what is really the simplest way of achieving this, I can somehow appreciate the enthusiasm with which the author describes his "inventive" solution. It works, but a simple `-1*abs($num)`

would have worked just as well.