-1

Okay so I am designing a tracking software for a company. I have almost completed my software and now I realised that Bank Cheque Numbers can contain leading zeroes. Okay so for some function I need to add a certain number to this Cheque Number but I need to retain the leading zeroes. For Ex, 0701 + 2 should give me 0703 instead of 703. Also the size of the Cheque Number is not fixed so that i can add remaining digits as zero.

2 Answers2

1

you have to get the length of your initial string, add your value and then use str_pad to add again your leading zeros

$initial = "0123";
$length = strlen($initial); // save the length
$result = $initial + 2; // add your value (result is 125)
$final = str_pad($result, $length, '0', STR_PAD_LEFT); // add the leading zeros to the initial length
echo $final; // will echo "0125"
ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
0

Use "sprintf" to give a fixed length to a number. (with leading zeros)
Try below code

<?php
$value = 701 + 3; //do your calculation

$final_value = sprintf('%04d', $value); //give a fixed length to value 

echo $final_value; 
Rumesh
  • 402
  • 4
  • 15