ggirtsou
ggirtsou

Reputation: 2048

PHP increase number by one

This is a tricky one: I want to add +1 to this number: 012345675901 and the expected result is: 012345675902. Instead I get: 2739134 when I do this:

echo (012345675901+1);

When I try:

echo ('012345675901'+1);

I get this: 12345675902 which is pretty close to what I need, but it removes the leading zero.

When I do this:

echo (int) 012345675901;

I get 2739133. I also tried bcadd() without success:

echo bcadd(012345675901, 1);

which resulted in 2739134.

I know I am missing something here. I would really appreciate your help!

UPDATE 1 Answer 1 says that the number is octal:

function is_octal($x) {
    return decoct(octdec($x)) == $x;
}

$number = is_octal(012345675901);
echo var_dump($number);

The above returns false. I thought I needed to convert this from octal to a normal string but didn't work. I can't avoid not using the above number - I just need to increment it by one.

EDIT 2

This is the correct code:

$str = '012345675901';

$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros

Thank you everyone for your help! The above code produces: 012345675902 as expected

Upvotes: 3

Views: 1377

Answers (2)

syrkull
syrkull

Reputation: 2344

please see the code for explanation.

$str = "012345675901"; // your number
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190943

The leading 0 is treating your number as octal.

The leading 0 you need for output as a string, is a purely a representation.

Upvotes: 8

Related Questions