three3
three3

Reputation: 2846

Incrementing a string by one in PHP

I am struggling to find a way to increment a specific pattern required. For each new member, they are given a unique ID such as ABC000001. Each new members ID should increment by one. So the second member's ID would be ABC000002. I am using PHP and MySQL to keep track of each member but I have not been able to come up with a way to properly increment using the string format above.

What is the best way to approach this?

Upvotes: 0

Views: 3154

Answers (4)

Matt Smith
Matt Smith

Reputation: 91

just use the PHP increment operator ++

as long as you've sufficient leading zeros in the pattern, then PHP will correctly increment the numeric component

This code:

<?php
$name = 'ABC0000098';
print ++$name . PHP_EOL;
print ++$name . PHP_EOL;
print ++$name . PHP_EOL;

Outputs:

ABC0000099
ABC0000100
ABC0000101

Read more in the PHP docs: https://www.php.net/manual/en/language.operators.increment.php

  • aha - just saw there is already a link to a similar example in the comment posted by "axiac" above

Upvotes: 0

Andri
Andri

Reputation: 461

Possible answer without regex. Runs through each character and checks if it is a number or not. Then uses sprintf() to make sure leading 0s are still there.

$str = "ABC000001";
$number = "";
$prefix = "";
$strArray = str_split($str);
foreach ($strArray as $char) {  
    if (is_numeric($char))  {
        $number .= $char;   
    } else {
        $prefix .= $char;   
    }
}
$length = strlen($number);

$number = sprintf('%0' . $length . 'd', $number + 1);
echo $prefix . $number;

This works for this instance but would not work if the prefix had numbers in it.

Upvotes: 0

Bruno Ribeiro
Bruno Ribeiro

Reputation: 1411

You can extract only digits using regex to increment and using str_pad for create a prefix :

$memberid = 'ABC000001';
$num = preg_replace('/\D/', '',$memberid);
echo sprintf('ABC%s', str_pad($num + 1, "6", "0", STR_PAD_LEFT));

Upvotes: 2

Dave
Dave

Reputation: 5190

As @axiac mentions this is probably not a good idea but it's pretty easy to manage.

$memberid = 'ABC000001';
list($mem_prefix,$mem_num) = sscanf($memberid,"%[A-Za-z]%[0-9]");
echo $mem_prefix . str_pad($mem_num + 1,6,'0',STR_PAD_LEFT);

Split your current member number into the alpha and numeric parts then put them back together bumping the number when you do it. I use this as a function and pass the previous ID and what I get back is the next ID in the sequence.

Upvotes: 5

Related Questions