3

How to allow PHP calculation 0 appears if example :

$a = "00001";
$b = "00005";

$total = $a + $b;

Expected result is : 00006

Including and keep 0000 appears.

I tried but the result always : 6

John Conde
  • 217,595
  • 99
  • 455
  • 496
bDir
  • 173
  • 1
  • 2
  • 11

5 Answers5

7

Just do normal math and then add the zeros back in front at the end:

$a = "00001";
$b = "00005";

$total = $a + $b;
$total = sprintf("%05d", $total );

or

$total = str_pad($total , 5, "0", STR_PAD_LEFT);
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

You might want to try and prepend the needed 0's

<?php
$total = 6;
$total_padded = sprintf("%05s", $num);
echo $num_padded; // returns 00006
?>

I haven't tested it but it should work :)

1
  <?
   str_pad($num, 5 , '0', STR_PAD_LEFT);
  ?>
Rubensito
  • 102
  • 6
1
 <?php
   str_pad($total, 5, '0', STR_PAD_LEFT);
  ?>
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
1

I assume that the value is integer so you should use intval. If it is float use floatval

$a = "00001";
$b = "00005";

print intval($a);
print intval($b);
print intval($a)+intval($b);

than add the leading zeros

melanholly
  • 762
  • 1
  • 9
  • 20