SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot samohtwerdna's Avatar
    Join Date
    Jul 2007
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    help with printf()

    Hello,

    I think I want to use printf(); but not sure.
    My problem is that I need to output a number that has 5 digits. I am grabing a number from a db query and if that number is say 342 I want to add 0's infront of that number so that it becomes 00342.

    Can printf() do that??

    if so - could I also be directed how I might add a space between each number?
    0 0 3 4 2

    Thanks for any help,
    Finding beauty in the simple.
    Five Elephants

  2. #2
    SitePoint Wizard bronze trophy Immerse's Avatar
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    1,661
    Mentioned
    7 Post(s)
    Tagged
    1 Thread(s)
    I think you can do it with (s)printf() but str_pad() should work just as well:

    PHP Code:
    $string '342';
    $string str_pad($string5'0'STR_PAD_LEFT);
    echo 
    $string// 00342 
    Edit>>
    To add the spaces, try this:
    PHP Code:
    $string implode(" "str_split($string)); 

  3. #3
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Here's the (s)printf alternative.
    PHP Code:
    <?php
    $num 
    sprintf('%05d'342); #00342

    $num implode(' 'str_split($num)); #0 0 3 4 2
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •