Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – keeping the 0 non-significant in the sum

In the database I have a field with values such as C50003.

I have a function that divides this value into: C5 and 0003.

Now I need to add 1 to 0003, which would become 0004.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is that when I do the sum (0003 + 1) the result is 4 and not 0004. (I have already tried doing 0003 + 0001, but nothing changes).

To fix this error I would have to count the number of initial 0’s and put them back to the final result, but that would be a laborious check.

Is there any way to keep those 0’s?

>Solution :

As easy way:

$value = '0003';
$intValue = (int) $value;
$newValue = $intValue + 1;
$formattedValue = str_pad($newValue, strlen($value) - strlen($intValue) + 1, '0', STR_PAD_LEFT);
echo $formattedValue; // 0004

$value = '0012'; // => 0013
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading