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.

Okay I got it now :slight_smile:

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 :slight_smile:

+1
Concise titles will certainly increase your chances of getting help.

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.

Oops, indeed I did!

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…


  $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 :slight_smile:

Hi jemz,

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

$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 ;?

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:


$serial = "xs-00001";
$xx = substr($serial, 3);
$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?

That makes sense. I didn’t think of using sprintf.
Nice one.

Making the assumption that it always starts with ‘xs-’, you could do this:

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).

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.


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

To be fair, so does String#next

e.g.

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:

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

I suppose this is a little bulky old-school but it’s what I came up with.

<?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:

preg_match('/^([a-z-]+)(\\d+)$/i', $serial, $matches);

You then get an array ($matches) containing the following:


array
  0 => string 'xs-00001' (length=8)
  1 => string 'xs-' (length=3)
  2 => string '00001' (length=5)

Nice fretburner. Good to know.

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-.

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.

Yup, fair point. I was only messing about and seeing what was possible.

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.

You could do it in Python like this:

oldSerial = "xs-00001"
parts = oldSerial.split('-')
newSerial = "{0}-{1:05d}".format(parts[0], int(parts[1]) + 1)

print newSerial

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

Can anyone add any more languages?

I know this is not for web languages but i will just post this

Using Java.


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));

    }

}