Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

leading zeros problem

Status
Not open for further replies.

webslinga

Programmer
Jun 20, 2006
55
US
Hey all,
I am creating a function that will take in the maximum value from a field in my database. I need to process that string and pass the id into a text field. I need to add leading zeros when appropriate (either 1 or 2 zeros). However, this does not work. I tried to do it with str_pad according to a previous thread in this forum but it did not work for me either. Here's a snippet of my code:

Code:
$nextOMSID = $omsids[0] + 1;

      if(strlen($nextOMSID) == 1)
        $nextOMSID = str_pad($nextOMSID, 2, '0', STR_PAD_LEFT);
      else if(strlen($nextOMSID) == 2)
        $nextOMSID = str_pad($nextOMSID, 1, '0', STR_PAD_LEFT);
      else
        $nextOMSID = str_pad($nextOMSID, 0, '0', STR_PAD_LEFT);

I also looked into sprintf and printf but they output the value and I just need to assign it to something else. Any feedback is welcome. Thanks.
 
could you do this instead:
Code:
$nextOMSID = $omsids[0] + 1;
if ($nextOMSID < 10):
 $nextOMSID = "00" . $nextOMSID;
elseif ($nextOMSID < 100):
 $nextOMSID = "0" . $nextOMSID;
endif;
 
I tried doing the following code and I can echo the result out and verify it's true. It's just that when I place it as a value in the textfield the leading zero gets stripped off. Any ideas?

Code:
      $nextOMSID = $omsids[0] + 1;
      $nextOMSID = sprintf("%03d", $nextOMSID);
 
using your code
Code:
$nextOMSID = 2;
$nextOMSID = sprintf("%03d", $nextOMSID);
echo "<form action=\"{$_SERVER['PHP_SELF']}\" method=\"post\">";
echo '<input name="test" type="text" value="'.$nextOMSID.'" />';
echo "<input type=\"submit\" value=\"submit\" name=\"submit\" />";
if (isset($_POST)):
 echo "<hr/><pre>";
 print_r($_POST);
endif;
i get the expected results.
Code:
Array
(
    [test] => 002
    [submit] => submit
)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top