Home » Php » How to keep leading zeros in PHP integer

How to keep leading zeros in PHP integer

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am working with an api and need to pass it the ClientID as an integer. The problem is that some of the ID’s start with leading 0’s. When I pass the integer to the API…PHP is cutting off the leading zero’s which makes the ClientID inaccurate. I have tried passing the ID as a string to keep the zero’s but the API expects an integer.

Example: ClientID = 00061423 when I pass it to the API it gets shortened to 61423 leading the request to fail because it can’t find that client.

Is there a way to have PHP keep the leading zero’s on integers?

How to&Answers:

You cannot keep leading zeros in integer. You can either keep them in a string or add at output time, using sprintf(), str_pad(), etc.

Answer:

Pass it as a string; The zeros will be maintained.

Answer:

use str_pad

str_pad($var, $numZeroesToAppend, '0', STR_PAD_LEFT)