Jump to content

Adding 1 to number


dreampho

Recommended Posts

Hi all.

 

I am trying to add 1 to a number. The problem I have is that the number is 4 digits long.

 

So for example the number could be 0007. I add one and it returns 8. I need it to return 0008.

 

<?php
$next = 0007 + 1;
echo $next;
?>

 

Can anyone show me how I can get the number to be 4 digits?

 

Thank you

Link to comment
https://forums.phpfreaks.com/topic/260728-adding-1-to-number/
Share on other sites

First problem is here:

$next = 0007;

PHP will automatically make it an int (number) type. It won't have any leading zeroes. So let's say it's a string instead.

$number = '0007';

Now we can get the length of the number.

$number_length = strlen($number);

Then we can start adding one to the number:

$number++;

And finally to output it:

echo str_pad($number, $number_length, '0', STR_PAD_LEFT);

http://php.net/manual/en/function.str-pad.php

 

<?php
$number = '0007';
$number_length = strlen($number);
$number++;
echo str_pad($number, $number_length, '0', STR_PAD_LEFT);
?>

Link to comment
https://forums.phpfreaks.com/topic/260728-adding-1-to-number/#findComment-1336312
Share on other sites

str_pad() works, but personally I prefer sprintf.

$current = "0052"; // absolutely must be a string!
$next = sprintf("%04u", $current + 1);

 

Ah, yes. I just tried to break it down to as easy bites as possible. I'd say sprintf is a bit more complicated to understand, but might just be me! lol

 

If the number has variable length:

$current = "0052"; // absolutely must be a string!
$next = sprintf('%0'.strlen($current).'u', $current + 1);

 

If the number has pre-defined length:

$current = 52; // does not need to be a string, can be a number!
$length = 4; // the length, the amount of digits
$next = sprintf('%0'.$length.'u', $current + 1);

 

both examples using str_pad() instead:

$current = '0052'; // absolutely must be a string!
$next = str_pad($current, strlen($current), '0', STR_PAD_LEFT);

$current = '52'; // does not need to be a string, can be number! 
$length = 4; // length, number of digits.
$next = str_pad($current, $length, '0', STR_PAD_LEFT);

 

They are very similar, but sprintf has more functionality, and is therefor a bit more complicated to use for new users in my opinion.

Link to comment
https://forums.phpfreaks.com/topic/260728-adding-1-to-number/#findComment-1336319
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.