0

How do I show the leading zeros of a field returned from mysql? For example: in a given field, I have the value "000A46" and I need to display the 3 zeros on the screen. However, PHP hides them. Shows only "A46".

Ps. "000A46" was just an example. It could be "000A4658" or "00000000S" and so on...

  • 1
    PHP won't remove the leading zeroes from a string unless you're doing something else to it like `number_format`. Can you show us the actual code involved, and the data type of the field in MySQL? – ceejayoz Feb 02 '19 at 14:03
  • 1
    @ceejayoz is right, PHP won't trim leading 0's from string. Can you please tell us your column type? Better add some code. – Khurram Shahzad Feb 02 '19 at 14:14

1 Answers1

0

Just to this:

$val = "A46";
$val = str_pad ( $val , 6, "0", STR_PAD_LEFT );
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • Thank you Pablo. But "000A46" was just an example. It could be "0A4658" or "00000S". – Jetro Bernardo Feb 02 '19 at 13:53
  • @JetroBernardo This code works fine for that (with the one small adjustment I added to have it left-pad instead of right-pad). – ceejayoz Feb 02 '19 at 14:02
  • $var = 000046; echo str_pad ($var , 6, "0", STR_PAD_LEFT); // this shows "000038" – Jetro Bernardo Feb 02 '19 at 14:14
  • Hello @JetroBernardo! I understood the first time that "A46" was just an example. Likewise, the code I showed you was just an example. You need to replace `$val = "A46"` with whatever you get from your MySQL query... – Pablo Santa Cruz Feb 02 '19 at 14:14
  • 1
    Thanks @ceejayoz for pointing this out! – Pablo Santa Cruz Feb 02 '19 at 14:14
  • @JetroBernardo `$var = 000046;` means you've got octals (base 8 instead of base 10) in play. That's going to mess **everything** up. http://php.net/manual/en/language.types.integer.php "To use octal notation, precede the number with a 0 (zero)." MySQL shouldn't be giving you octal values; it should be giving you *strings*. `$var = '000046';` will work fine. – ceejayoz Feb 02 '19 at 14:37