user213559
user213559

Reputation:

How to add a value to an existing value in php

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...

Upvotes: 1

Views: 335

Answers (5)

VolkerK
VolkerK

Reputation: 96159

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 ;-) )

Upvotes: 1

Lukman
Lukman

Reputation: 19129

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);

Upvotes: 0

codaddict
codaddict

Reputation: 454960

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


?>

Upvotes: 3

Adam Kiss
Adam Kiss

Reputation: 11859

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);

Upvotes: 0

Petah
Petah

Reputation: 46040

you could try:

str_pad($result, 5, "0", STR_PAD_LEFT);

Upvotes: 1

Related Questions