I have this code:
$i = '0001';
$j = $i 1;
I want to get 0002 but it give me only 2 How can I plus $i and keep that 000?
Thank you
CodePudding user response:
PHP took a useful feature from Perl: the ability to increment strings, using
. Unfortunately, it didn't do it very well. If you increment "A0001"
, you get "A0002"
; but if you increment "0001"
, you get 2
(as opposed to original Perl, which would give you "0002"
). But, you can cheat:
$i="0001";
$j=":$a";
$j ;
$j=substr($j, 1);
This is more to both illustrate a cool thing not many people might be aware of, and how it was misimplemented, than to provide a real solution; I would definitely prefer to see a str_pad
or sprintf
solution in my code.
CodePudding user response:
You can use str_pad to keep the leading zeroes.
Code here,
<?php
$i = '0001';
$val = $i 1;
echo str_pad($val,4,"0",STR_PAD_LEFT); // 0001
?>
Click to learn more about str_pad
CodePudding user response:
Maybe this can give you an idea:
$i = '0001';
$i = intval($i);
$i ;
$a = '000';
$result = $a.$i;
echo $result;
The .
between $a
and $i
is concatenating the variables into a string, keeping every character in them.
The code above will output 0002
Check it here: http://sandbox.onlinephpfunctions.com/code/fc2bd5861a6c0d937568b067e98e06977741019c
If you want to keep all leading zeroes, you could count them separately and increment it like this. Of course, this is something whipped out quickly and I'm 100% certain there are much better ways of doing this out there.