PHP integer value being modified for no apparent reason

Asked

Viewed 38 times

1

Folks I’m having trouble with changing an integer number starting with zero.

$agencia = 0736;
$conta = 999999;

$agencia = intval($agencia); 
$conta = intval($conta); 
echo($agencia); //resultado 478

Even without the intval was giving the same problem. However its putting in place of zero the number 1 for example. Will print correctly(1736). ::PHP version 7.0::

  • Why not treat it as string? I believe it will solve your problem!

  • I tried, but as I pass the information to a class, when I rescue is already changed the value.

3 answers

2

You can use the sprintf

sprintf('%08d', 1234567);

output: 012345678

8d is the amount of digits you want

1

Numbers started with zero, since valid, are interpreted based on 8 (octal), ie 02345674 was interpreted based on 8 and its representation based on 10 is 641980.

The warning manual on this on the page about integers

That one website does base 8 x base 10 conversions

if you do so I believe it will work (int)$agencia;

  • 1

    It did not work because this value I send to a class, and within the class already arrives converted as well. Luckily, in the link manual you passed, there’s a five-year commentary on a guy with the same problem. And the solution is ridiculous for a robust language like PHP.

  • puts here the solution to help the crowd then! want to edit my answer or create another is at will!

  • 1

    I put as an answer. Thanks!

1


@Lodi thanks for the help, in the comments of the manual I found this "solution".

$agencia = "0736" + 0;

In this way the decimal Octa is canceled and passes the value without the zero: 736; But then you just pick it up and put it back in with the function:

str_pad($agencia, 4 , '0' , STR_PAD_LEFT);

That completes left character quantities with zero.

Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.