Print a sequence of numbers in PHP with the correct (+/-) sign

I need to print some numbers in a sequence with + and - between them. However, I don't know beforehand which number is going to be positive and which is going to be negative. Currently, I echo them like this:

echo "$a + $b + $c + $d + $e + $f";

Let's say the values of $a to $f are all positive. I will get something like: 5 + 10 + 12 + 18 + 9 + 7.

However, if some of the values are negative, I will get something like 5 + -10 + 12 + -18 + 9 + - 7. The ideal output in this case would have been 5 - 10 + 12 - 18 + 9 - 7.

Please not that I don't want to calculate the final result of addition or subtraction. I just want to print it all on the webpage with correct signs.

I could do so by writing 6 nested if() blocks but that seems like a lot of work and doing it every time will be error prone. Is there anything clever that I can do to output the right sign.

5 answers

  • answered 2018-07-11 05:55 Lovepreet Singh

    Need to check for each variable manually like this:

    echo "$a " . ($b < 0 ? " - " . abs($b) : " + $b") . ($c < 0 ? " - " . abs($c) : " + $c") . ($d < 0 ? " - " . abs($d) : " + $d") . ($e < 0 ? " - " . abs($e) : " + $e") . ($f < 0 ? " - " . abs($f) : " + $f");
    

  • answered 2018-07-11 05:57 nageen nayak

    you can use php sprintf function.

    function formatNum($num){
        return sprintf("%+d",$num);
    }
    

    or

    function formatNum($num) {
      $num = (int) $num; // or (float) if you'd rather
      return (($num >= 0) ? '+' : '-') . $num; // implicit cast back to string
    }
    

    for more detail please read it :- http://php.net/manual/en/function.sprintf.php

  • answered 2018-07-11 05:59 Chirag

    try this

    $a = 10;

    $b=-20;

    $text = $a." ".$b;

    $text= str_replace(" ", "+", $text);

    echo $text;

    OUTPUT

    10+-20

  • answered 2018-07-11 06:06 Phil

    Put the numbers in an array and use array_reduce to create the string

    $numbers = [5, -10, 12, -18, 9, -7];
    $first = array_shift($numbers);
    
    echo array_reduce($numbers, function($str, $num) {
        return $str . sprintf(' %s %d', $num < 0 ? '-' : '+', abs($num)); 
    }, $first);
    

    Demo ~ https://eval.in/1034635

    This way you can handle an arbitrary amount of numbers without duplicating logic everywhere.

  • answered 2018-07-11 06:19 Tom Regner

    The easiest way would be to correct the operator appearance in the final string:

    $s = '5 + -10 + 12 + -18 + 9 + - 7'; // result of interpolation or concatenation
    $s = str_replace('+ -', '- ', $s);
    // => "5 - 10 + 12 - 18 + 9 -  7"
    

    If this is possible for you, this is as fast as it gets -- no looping (in php), no treating each number one at a time with a conditional. If you loop anyway, I'd recommend @Phils suggestion with array_reduce -- functional style php -- adapted to your needs.