-1

I need a little help with some PHP code. I looked at the examples for doing this with JavaScript and used that as the basis for a PHP implementation. Two issues I haven't be able to resolve. I still get a leading 1 at the start of the string. I also get fewer zeros than specified once the values have trailing zeros (i.e 10, 20, etc).

$num = 2;
$numZeros = 5;


function listRiskNumber($num, $numZeros) {
    $n = abs($num);
    $zeros = max(0, $numZeros - strlen(floor(json_encode($n))));
    $zeroString = substr((pow(10,$zeros)),0,5);
    if( $num < 0 ) {
        $zeroString = '-' + $zeroString;
    }

    return $zeroString + $n;
}

$row = listRiskNumber($num, $numZeros);
echo $row;

I want to turn the leading 1 into a zero, and ensure trailing zeros don't get cut off. Any help would be greatly appreciated.

airider74
  • 390
  • 3
  • 14
  • 1
    If https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php helps, then it can be marked as duplicate. Not sure as the code you show is a bit difficult to understand. – Nigel Ren Aug 04 '19 at 16:30
  • Nigel Ren and ehymel. That's the ticket. We can mark this as a duplicate. – airider74 Aug 04 '19 at 18:38
  • Nigel, This was derived from a Javascript I found searching for similar solutions here. – airider74 Aug 04 '19 at 18:43
  • Nigel, The max(0, ...) code was to determine the number of leading zeros to display based on the size of the $num variable. $zeroString was supposed to create the formatted output based on the max output. The $num less than zero deals with negative numbers if encountered. – airider74 Aug 04 '19 at 18:50

1 Answers1

-1

sprintf("%08d", $value);

Solved the problem. Thanks all for the quick answers.

airider74
  • 390
  • 3
  • 14