tags:

views:

65

answers:

5

Consider my variable $result to be 01212.... Now if i add 1 to my variable i get the answer 1213,but i want it to be 01213.... My php code is

echo sprintf('%02u', ($result+1));

Edit:

Answers to this question works.. But what happens if my variable is $result to be 0121212 in future...

+1  A: 

you could try:

str_pad($result, 5, "0", STR_PAD_LEFT);
Petah
-1 one for complicated solution, +1 for introducing me to str_pad :]
Adam Kiss
A: 

Read here: http://php.net/manual/en/function.sprintf.php

in sprintf, you also has to specify length you want - so in your case, if you want any number to be shown 5chars long, you haveto write

echo sprintf ('%05d', $d); // 5 places taking decimal

or even better

printf ('%05d', $d);
Adam Kiss
@Adam what happens if my variable becomes 0121212... Will your syntax work for this...
chandru_cp
then you simply use `%07d` isntead of `%05d` - you have to tell printf/sprintf how many palces should your numbers take - it can't do it for you.
Adam Kiss
alsou you can swap `d` for `u` - complete list of possible values for type of variable `printf`-ed, go to that link I posted :]
Adam Kiss
+3  A: 

You can use %05u instead on %02u

echo sprintf('%05u', ($result+1));

EDIT:

To generalize it:

<?php

$result = "0121211";

$len = strlen($result+1) + 1;

printf("%0${len}d", ($result+1)); // print 0121212


?>
codaddict
@codaaddict what happens if my variable becomes 0121212... Will your syntax work for this
chandru_cp
Oh..seems like you want a generalized solution..I've updated my answer.
codaddict
@codaddict ur edit didnt work 4 me...
chandru_cp
For what case did it fail ?
codaddict
+1  A: 

Maybe I'm missing something here but it could be as simple as

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

edit:

$test = array('01212', '0121212', '012121212121212', '-01212');
foreach( $test as $result ) {
  $result = '0'.($result+1);
  echo $result, "\n";
}

prints

01213
0121213
012121212121213
0-1211

( you see, there are limitations ;-) )

VolkerK
maybe with a `strval` will be better:`echo '0'.strval($result+1);`
Donny Kurnia
strval() or implicit cast to string ...what's the difference here? And in case you want to avoid any implicit cast `$result = '0' . strval(intval($result)+1);` would be more consistent.
VolkerK
A: 

Seems like you want to have a '0' in front of the number, so here would be the simplest :P

echo '0'. $result;

Or if you insist on using sprintf:

$newresult = $result + 1;
echo sprintf('%0'.(strlen(strval($newresult))+1).'u', $newresult);
Lukman