简体   繁体   中英

How to add number in string if string is combination of letter and number?

I want to increment IDT100 this string ( IDT100, IDT101, .....IDT1000 etc ) which dynamic.

I tried below code

<?php

$cart_billno = "IDT100";

echo $cart_billno += 1 ;//....1st try

echo $cart_billno = $cart_billno + 1 ;//...2 nd try

?>

Answer i got id 1

I check php official site

then i tried

<?php 

$var = 1;

echo $cart_billno = $cart_billno + $var ;//......3 rd try

?>

Answer i got id 1

What is wrong in my code?

Use preincrement instead:

$cart_billno = "IDT100";
echo ++$cart_billno; // IDT101

Or use a normal for loop:

$cart_billno = 'IDT';
for($i = 100; $i <= 1000; $i++) {
    echo $cart_billno.$i . '<br/>';
}
$cart_billno = "IDT";

$i = 99;
while (++$i < 1001) {
    echo $cart_billno . $i ;
}

Will print IDT100 To IDT1000

If you need to increment the value more than 1 at the same time use something like:

$cart_billno = "IDT100";
echo substr($cart_billno, 0, 3) , (substr($cart_billno, 3) + 99); // IDT199

Which would be a cleaner solution in my opinion than increase an alphanumeric string by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM