开发者

How to generate an alphanumeric incrementing id in PHP?

I have system in PHP in which I have to insert a Number which has to like

PO_ACC_00001,PO_开发者_运维百科ACC_00002,PO_ACC_00003.PO_ACC_00004 and so on

this will be inserted in Database for further reference also "PO and ACC" are dynamic prefix they could different as per requirement

Now my main concern is how can is increment the series 00001 and mantain the 5 digit series in the number?


>> $a = "PO_ACC_00001";
>> echo ++$a;
'PO_ACC_00002'


You can get the number from the string with a simple regex, then you have a simple integer.

After incrementing the number, you can easily format it with something like

$cucc=sprintf('PO_ACC_%05d', $number);


Create a helper function and a bit or error checking.

/**
 * Takes in parameter of format PO_ACC_XXXXX (where XXXXX is a 5
 * digit integer) and increment it by one
 * @param string $po
 * @return string
 */
function increment($po)
{
    if (strlen($po) != 12 || substr($po, 0, 7) != 'PO_ACC_')
        return 'Incorrect format error: ' . $po;

    $num = substr($po, -5);

    // strip leading zero
    $num = ltrim($num,'0');

    if (!is_numeric($num))
        return 'Incorrect format error.  Last 5 digits need to be an integer: ' . $po;

    return ++$po;

}

echo increment('PO_ACC_00999');


Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation.

<?php 
    $num_of_ids = 10000; //Number of "ids" to generate.
    $i = 0; //Loop counter.
    $n = 0; //"id" number piece.
    $l = "PO_ACC_"; //"id" letter piece.

    while ($i <= $num_of_ids) { 
        $id = $l . sprintf("%05d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
        echo $id . "<br>"; //Print out the id.
        $i++; $n++; //Letters can be incremented the same as numbers. 
    }
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜