SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 31
  1. #1
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post How do i add this

    Hi, how can i add 1 in this

    $var = "xs-00001";

    the output must be like this.

    xs-00002

    Thank you in advance.

  2. #2
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay I got it now

  3. #3
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,267
    Mentioned
    33 Post(s)
    Tagged
    5 Thread(s)
    Hey jemz, glad you could solve your problem.

    Could you try to make your thread titles a bit more informative please? Something like "How do I an ID by 1 each time?" would be more informative and we won't be confused by threads with similar names

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Quote Originally Posted by fretburner View Post
    Could you try to make your thread titles a bit more informative please?
    +1
    Concise titles will certainly increase your chances of getting help.

    Quote Originally Posted by fretburner View Post
    "How do I an ID by 1 each time?"
    I think you forgot the word "increment", as in "How do I increment an ID by 1 each time?"

    Also jemz, it might be nice if you posted your solution, as this could help others in the future that have the same issue as you.

  5. #5
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,267
    Mentioned
    33 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by Pullo View Post
    I think you forgot the word "increment", as in "How do I increment an ID by 1 each time?"
    Oops, indeed I did!

  6. #6
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also jemz, it might be nice if you posted your solution, as this could help others in the future that have the same issue as you
    Okay this how i solved my problem,please correct me if i am wrong...

    PHP Code:
      $serial "xs-00001";
      
    $xx substr($serial,3);

      
    $result_serial str_pad(((int)$xx 1),5,"0",STR_PAD_LEFT);

     
    $result_serial "xs-".$result_serial;
     echo 
    $result_serial
    Cheers

  7. #7
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Hi jemz,

    I would be tempted to do it like this in the hope that it is a little more readable:

    Code PHP:
    $serial = "xs-00001";
    preg_match('/^xs\-(\d+)$/', $serial, $matches);
    $increment = intval($matches[1]) + 1;
    $new_serial = "xs-" . str_pad($increment, strlen($matches[1]), "0", STR_PAD_LEFT);
    echo $new_serial;

    Not sure if this is the best way, as PHP is not really my fort.
    Any thoughts @fretburner ;?

  8. #8
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,267
    Mentioned
    33 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by Pullo View Post
    Any thoughts @fretburner ;?
    I guess it depends on the context: Where is the original serial number coming from? Will it always start 'xs-' or, if not, will the prefix always follow the same pattern (two letters and a dash)?

    Assuming the prefix is constant, I might do something like this:
    PHP Code:
    $serial "xs-00001";
    $xx substr($serial3);
    $new_serial sprintf('xs-%1$05d'$xx 1);
    echo 
    $new_serial
    I've always read that PHP's string functions were faster than using regex, so I've stuck with substr. I've used sprintf to format the string simply as it's more compact - not sure if it's more or less understandable at a glance though. Also, I'm not explicitly casting $xx to an int, as adding 1 should cause PHP to do that, and I've specified the parameter as a decimal value to sprintf.

    Off Topic:

    Pullo, just out of interest, how would you do this in Ruby?

  9. #9
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Quote Originally Posted by fretburner View Post
    I've always read that PHP's string functions were faster than using regex, so I've stuck with substr. I've used sprintf to format the string simply as it's more compact - not sure if it's more or less understandable at a glance though. Also, I'm not explicitly casting $xx to an int, as adding 1 should cause PHP to do that, and I've specified the parameter as a decimal value to sprintf.
    That makes sense. I didn't think of using sprintf.
    Nice one.

    Quote Originally Posted by fretburner View Post
    Off Topic:

    Pullo, just out of interest, how would you do this in Ruby?
    Making the assumption that it always starts with 'xs-', you could do this:

    Code Ruby:
    serial = "xs-00001"
    new_serial = "xs-" + serial.split("-")[1].next
    puts new_serial

    This is taking advantage of the fact that the Ruby String class has several methods that let you produce successive strings — that is, strings that increment, starting at the rightmost character (next being one of them).
    Last edited by Pullo; Aug 22, 2013 at 10:45.

  10. #10
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    How about javascript?
    A generic function, for any given separator and for any given length for the zero padded number, that also accounts for number going over their initial unit.

    Code:
    function strInc(str, sep){
        var arr = str.split(sep);
        arr[1] = (Array(arr[1].length).join("0") + (parseInt(arr[1]) + 1)).slice(-arr[1].length);
        return arr.join(sep);
        
    };
    console.log(strInc("xx-00001", "-"));
    console.log(strInc("yyz<>0000019", "<>"));
    =========================================
    xx-00002
    yyz<>0000020

  11. #11
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Quote Originally Posted by myty View Post
    That also accounts for number going over their initial unit.
    To be fair, so does String#next

    e.g.

    Code Ruby:
    serial = "xs-99999"
    new_serial = "xs-" + serial.split("-")[1].next
    puts new_serial
     
    => xs-100000

    I like your idea of passing in the separator, to make it more generic.

    And here's another JS version, just for fun:

    Code JavaScript:
    var serial = "xs-00001",
        new_serial = serial.replace(/^xs\-(\d+)$/, function(match, num) {
          return 'xs-' + ( Math.pow(10, num.length) + ~~( +num + 1) ).toString().substring( 1 );
        });
     
    console.log(new_serial);
     
    => xs-00002

  12. #12
    SitePoint Evangelist bronze trophy
    Join Date
    Feb 2013
    Posts
    510
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    I suppose this is a little bulky old-school but it's what I came up with.
    PHP Code:
    <?php
     $var 
    "xs-00001";
     
    $num preg_replace("/[^0-9]/""",$var);
     
    $pad strlen($num); 
     
    $num $num 1;
     
    $NEWnum str_pad($num$pad'0'STR_PAD_LEFT);      
     
    $pre preg_replace("/[0-9]/""",$var);
     
    $var =    $pre.$NEWnum;
     echo 
    $var;
    ?>

  13. #13
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,267
    Mentioned
    33 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by Drummin View Post
    I suppose this is a little bulky old-school but it's what I came up with.
    PHP Code:
    <?php
     $var 
    "xs-00001";
     
    $num preg_replace("/[^0-9]/""",$var);
     
    $pad strlen($num); 
     
    $num $num 1;
     
    $NEWnum str_pad($num$pad'0'STR_PAD_LEFT);      
     
    $pre preg_replace("/[0-9]/""",$var);
     
    $var =    $pre.$NEWnum;
     echo 
    $var;
    ?>
    It's a fair idea, grabbing the prefix via regex makes the code more reusable. You could simplify things a bit by using preg_match, which lets you grab both parts of the serial number in one pass:
    PHP Code:
    preg_match('/^([a-z-]+)(\d+)$/i'$serial$matches); 
    You then get an array ($matches) containing the following:
    Code:
    array
      0 => string 'xs-00001' (length=8)
      1 => string 'xs-' (length=3)
      2 => string '00001' (length=5)

  14. #14
    SitePoint Evangelist bronze trophy
    Join Date
    Feb 2013
    Posts
    510
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    Nice fretburner. Good to know.

  15. #15
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    And here's another JS version, just for fun:

    Code JavaScript:
    var serial = "xs-00001",
        new_serial = serial.replace(/^xs\-(\d+)$/, function(match, num) {
          return 'xs-' + ( Math.pow(10, num.length) + ~~( +num + 1) ).toString().substring( 1 );
        });
     
    console.log(new_serial);
     
    => xs-00002
    One other thing I would point out, is that in my javascript generic function I also handle the prefix (the part before the separator) without it being hardcoded, i.e. no serial.replace(/^xs\- or return xs-.

  16. #16
    SitePoint Evangelist bronze trophy
    Join Date
    Feb 2013
    Posts
    510
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    One other thing I would point out, is that in my javascript generic function I also handle the prefix (the part before the separator) without it being hardcoded, i.e. no serial.replace(/^xs\- or return xs-.
    And so does my solution with(out) resorting to JS.

  17. #17
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Quote Originally Posted by myty View Post
    One other thing I would point out, is that in my javascript generic function I also handle the prefix (the part before the separator) without it being hardcoded
    Yup, fair point. I was only messing about and seeing what was possible.

    Quote Originally Posted by Drummin View Post
    And so does my solution with resorting to JS.
    Shouldn't that be "without"

    Can anyone add any more languages?
    I know this is the PHP forum, but it would be fun to see what's possible.

  18. #18
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,267
    Mentioned
    33 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by Pullo View Post
    Can anyone add any more languages?
    I know this is the PHP forum, but it would be fun to see what's possible.
    You could do it in Python like this:
    Code Python:
    oldSerial = "xs-00001"
    parts = oldSerial.split('-')
    newSerial = "{0}-{1:05d}".format(parts[0], int(parts[1]) + 1)
     
    print newSerial

  19. #19
    SitePoint Member abilenewillson45's Avatar
    Join Date
    Aug 2013
    Location
    China
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can do it in java.Java takes everything as a string and by using ++ operator..that is increment operator u can increment ur string..bt i guess it will increment it alphabetically

  20. #20
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can anyone add any more languages?
    I know this is not for web languages but i will just post this

    Using Java.
    Code:
    public class IncrementNumberToString {
        public static void main(String []me){
            String word ="xs-9999";
    
            String x = word.substring(3,word.length());
    
            Integer xw = Integer.parseInt(x);
    
           System.out.print(String.format("xs-%04d",xw+1));
    
        }
    
    }

  21. #21
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,233
    Mentioned
    47 Post(s)
    Tagged
    1 Thread(s)
    I hope someone posts a solution in Erlang, zomg

  22. #22
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Can anyone add any more languages?
    I know this is the PHP forum, but it would be fun to see what's possible.
    How about haskell?

    Code:
    import Data.List.Split
    
    padL :: Int -> String -> String
    padL n s
        | length s < n = replicate (n - length s) '0' ++ s
        | otherwise = s
    
    strInc :: String -> String -> String
    strInc sep str = 
            let strarr = splitOn sep str
                zprefix = strarr !! 0
                znumber = strarr !! 1
            in zprefix ++ sep ++ padL ( length (znumber) ) ( show ( read ( znumber ) + 1 ) )
    Prelude> :l strinc
    [1 of 1] Compiling Main ( strinc.hs, interpreted )
    Ok, modules loaded: Main.
    *Main> strInc "-" "xs-00009"
    "xs-00010"
    *Main> strInc "<>" "yxs<>000099"
    "yxs<>000100"


    As with my javascript version, the length or the prefix are not hardcoded.

  23. #23
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hello,

    From my point of view the best way to do this if xs- is a constant

    Code:
    $number = $number++;
    $var = "xs-".$number;
    if you have the xs-0001 in a strig you can do

    Code:
    $number = explode("-","xs-0001")
    $number = $number[1];
    And then you can add the ++ line to add a number to the result.

    Hope it helps
    Last edited by VicHaunter; Aug 23, 2013 at 11:41. Reason: php code color

  24. #24
    SitePoint Evangelist bronze trophy
    Join Date
    Feb 2013
    Posts
    510
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    Really several php solutions are already provided including mine which would account for any prefix and handles floating zeros. The boys are just playing around with other coding languages.

  25. #25
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    How about Go(lang)?
    http://play.golang.org/p/_sUelH69s6

    I'm sure that my Haskell and Go examples can be further optimized, but so far JavaScript seems to be the winner.


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
  •