3

I want to convert an integer number to string while maintaining the leading 0's.

Is this posible in PHP?

$num = 0000003;

echo $num; // output: 3

echo (string)$num; // output: 3

// Wanted output: "0000003"

Edit:

I read the most questions before in SO, but I was curious if there was a possibility to keep the 0 and convert it to string in runtime, like the code example above echo (string)$num;.

Black Sheep
  • 6,604
  • 7
  • 30
  • 51

3 Answers3

6

you cant. 0000003 in the runtime is just 3.

you can add zeros manually using str_pad but you have to know target string length

str_pad((string)$num, $targetLenght, '0', STR_PAD_LEFT)
Binit Ghetiya
  • 1,919
  • 2
  • 21
  • 31
3

You have to instantiate the number as a string:

$num = "0000003";

If you instantiate it as number, it will be treated as such and your 0s will be lost.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
Auris
  • 1,309
  • 1
  • 9
  • 18
  • Thanks.. I know but what I want is to convert it as string `00003` to `"00003"` – Black Sheep Nov 25 '16 at 12:34
  • Where is your 00003 comming from? You can't convert it directly, but if it is read from DB or input maybe you can read it as string. – Auris Nov 25 '16 at 12:36
  • In a function for example: `do_something(00003);` I can not influence the input before – Black Sheep Nov 25 '16 at 12:39
  • no you can not, but that 00003 does not just magiaclly appear, if that is php generated it will be either 3 or "00003" instead of 00003 as a number 00003 simply can not exist. If that is some user or DB input, it must be handled at read time. Btw, php will allways read unknown format of 00003 as a string from input or DB. Could you expand your code example to show us where that 00003 comes from? – Auris Nov 25 '16 at 12:48
  • see thing is that like RiggsFolly has mentioned in the comment, a number 00003 simply can not exist, once it is stored in mem it will either be stored as 3 or as "00003" (depending on how it is created). – Auris Nov 25 '16 at 12:52
  • It can be a random number like `00123` or `12849`... I was only curious if there was a possibility to keep the `0` and convert it to string in runtime – Black Sheep Nov 25 '16 at 12:55
  • that is the whole point, if it is a number, it can't be 00123 as php wont allow that. – Auris Nov 25 '16 at 13:38
0

you can use strpad to do this :

str_pad($id , 8 , "0" , STR_PAD_LEFT);

This will make a string 8 characters long, zero padded to the left with the integer $id;

YvesLeBorg
  • 9,070
  • 8
  • 35
  • 48