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.
Asked
Active
Viewed 51 times
-1
-
2If it has leading zeroes, it's **not** a number (database zero-fill notwithstanding) – CD001 Jun 25 '18 at 15:55
-
3Possible duplicate of [Formatting a number with leading zeros in PHP](https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php) – dave Jun 25 '18 at 15:55
-
@CD001 I am saving it into Database as varchar. – Piyush Patil Jun 25 '18 at 15:56
-
So it's a string ... why are you trying to treat it as a number, when it isn't one? – CD001 Jun 25 '18 at 15:56
-
@aquaballin it's not. i already checked that thread after which I posted this question – Piyush Patil Jun 25 '18 at 15:57
-
You really shouldn't need the leading zeros. The banks can figure out the details without them. – aynber Jun 25 '18 at 15:57
-
just make it a string – samezedi Jun 25 '18 at 15:57
-
2use strlen to get the original length, cast to a number, compute your sum and then use str_pad ( http://www.php.net/manual/en/function.str-pad.php ) to add your leading zeros – ᴄʀᴏᴢᴇᴛ Jun 25 '18 at 15:58
-
@crozet thanks for the answer I really appreciate it. Can you post it as answer so that I can mark it correct – Piyush Patil Jun 25 '18 at 16:00
2 Answers
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