1

I would like to post a value to my MySQL database in this format;

01, 02, 03... 011, 012, 013... 0101, 0102, 0103, etc.

(with a 0 before each value).

If I do it like this "01+1" I (understandable) get the value 2 and not "02". is there a default php function that let's me set the default amount of characters or is there an other option?

I'm using laravel combined with eloquent and some own functions like so;

$lastSKU = $data->GetData('get', 'products', 'filter')->max('SKU');
$newValue = $lastSKU+1;

Thanks in advance.

prabhat gundepalli
  • 907
  • 3
  • 15
  • 39
RMCS
  • 383
  • 3
  • 17

1 Answers1

1

It sounds like you won't know how the format will be, if there is always a 0 in front it is easy enough to do

$value = '0'. ( $value + 1 );

PHP will automatically convert it to a number between the brackets and by adding a string to it it will become a string again.

Now if you do not know the the length or the padding in advance but you do need to keep the current padding I would suggest something like

$value = str_pad(($value + 1), strlen($value), '0', STR_PAD_LEFT);

Edit, str_pad is a bit slow these days, sprintf can do the same trick but much faster

$value = sprintf("%'.0" . strlen($value) . "d\n", ($value +1));
DarkMukke
  • 2,469
  • 1
  • 23
  • 31
  • thanks! this is what i needed, i missed the brackets. if there also a option for a default length? like 00000001 (8 characters for example) – RMCS Dec 03 '18 at 19:10
  • yes just replace `strlen($value)` with your default value – DarkMukke Dec 03 '18 at 19:11
  • also make sure to accept the answer and not just upvote it. – DarkMukke Dec 03 '18 at 19:13
  • fyi - I was curious about your claim that str_pad is slow so ran a quick benchmark using PHP 7.2.10. Results consistently show str_pad outperforming sprintf and getting the job done in about 1/2 the time. Granted I think this is really micro-optimizing since both functions were able to complete 1 million iterations in .1 and .2 seconds respectively. – But those new buttons though.. Dec 03 '18 at 20:43
  • @billynoah yeh i did the same a while back, but someone proved me wrong : https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php#comment-76360104 – DarkMukke Dec 03 '18 at 20:47
  • yeh but what happens if you crank up the values ? https://3v4l.org/1GLFD – DarkMukke Dec 03 '18 at 20:58