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!

very simple question.

Status
Not open for further replies.

alan123

MIS
Joined
Oct 17, 2002
Messages
149
Location
US
I have a variable say: $s=20, now I want to change it to string "0020", how can I do it in php? thanks.
 
Gotta be more specific... if you mean you want a zero padded four digit string...
Code:
$s = str_pad($s, '0', 4, STR_PAD_LEFT);

If you mean you want to pre-pend two zeros
Code:
$s = '00'.$s;

 
Here's a simple (and admitteldly stupid) answer. Please forgive me:
Code:
$s = 20;
$s = '0020';

The main contributor and master-expert of this forum, sleipnir214, has the following in his signature:

Want the best answers? Ask the best questions!
 
Actually I need the fixed length string($a is a 4 character string), so
Code:
$a='00'.$s;
doesn't work, as $s may have only one or more characters.

I also tried:
Code:
$s = str_pad($s, '0', 4, STR_PAD_LEFT);
but I still get 20(two characters), it looks both ways are not working.

any suggestion?

thanks.
 
If you need to output an integer as a four-digit string with whatever necessary leading zeros, I recommend that you use printf():

<?php
$a = 20;
printf ("%04u", $a);
?>





Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Well I gave the right function, just swapped two arguments.
Code:
str_pad($s,4,'0',STR_PAD_LEFT);

Anyway, sleipnir's answer is also very good, and you may consider sprintf if it's the method you want but you want to assign the variable. rather than output it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top