PHP and Numbers

Discussion in 'PHP' started by Omzy, Mar 16, 2009.

  1. #1
    I am retreiving a number from an ID field in the database, the number is stored in the database as 0036. I want to display this number but incremented by 1 in my PHP script. I tried doing this but instead of displaying 0037 it just displays 37. How can I make this work?

    This is what I tried doing:

    $value=$row['id']+1;
    Code (markup):
     
    Omzy, Mar 16, 2009 IP
  2. renlok

    renlok Well-Known Member

    Messages:
    457
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    110
    #2
    you would have to do something like
    
    $tmp = intval($row['id'] + 1);
    $len = strlen($tmp);
    if($len == 1)
     $value = '000'.$tmp;
    elseif($len == 2)
     $value = '00'.$tmp;
    elseif($len == 3)
     $value = '0'.$tmp;
    else
     $value = $tmp;
    
    PHP:
     
    renlok, Mar 16, 2009 IP
  3. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or, if you don't enjoy doing so much typing, you can just use:
    $value = sprintf("%04d", $row['id'] + 1);
    Code (markup):
     
    SmallPotatoes, Mar 16, 2009 IP
  4. Omzy

    Omzy Peon

    Messages:
    249
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Cheers SmallPotatoes. Will that function also work if the number is for example: 0123
    And I want it to increment by one to make it 0124
     
    Omzy, Mar 16, 2009 IP
  5. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yep, it will work with any number from 1-4 digits. If the number is more than 4 digits it will just leave it alone.

    e.g., 255 becomes 0255, but 12345 remains 12345. To change the number of digits it pads out to, just change the 4 in the first argument to sprintf.
     
    SmallPotatoes, Mar 16, 2009 IP
  6. Omzy

    Omzy Peon

    Messages:
    249
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Fantasic mate! Thanks for that :)
     
    Omzy, Mar 16, 2009 IP
  7. websecrets

    websecrets Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    str_pad would probably be the best way.
     
    websecrets, Mar 16, 2009 IP