Alessio Scalzo
Alessio Scalzo

Reputation: 3

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.

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?

Upvotes: 0

Views: 57

Answers (1)

7-zete-7
7-zete-7

Reputation: 745

As easy way:

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

$value = '0012'; // => 0013

UPD: Change strlen($value) - strlen($intValue) + 1 to strlen($value) on the advice of @user1597430.

Upvotes: 1

Related Questions