简体   繁体   中英

How to increment number after letter in PHP

I'm looking to increment a number after a certain letter.

I have a list of own Ids and i would like to increment it without write it manually each time i add a new id.

$ids = array('303.L1', '303.L2', '303.L3', '303.L4');

so i use the END() function to extract the last id from this array.

this is what i've tried but i cannot get a result.

        $i = 0;
        while($i <= count($ids)){

            $i++;
            $new_increment_id = 1;
            $final_increment = end($last_id) + $new_increment_id;

        }
        echo $final_increment;

New method, but it is adding me double dot between number and letter.

          $i = 0;
           while($i <= count($ids)){
            $i++;
            $chars = preg_split("/[0-9]+/", end($ids));
            $nums = preg_split("/[a-zA-Z]+/", end($ids));

            $increment = $nums[1] + 1;
            $final_increment = $nums[0].$chars[1].$increment;
        }

        //i will use this id to be inserted to database as id:
        echo $final_increment;

Is there another way to increment the last number after L ?

Any help is appreciated.

If you don't want a predefined list, but you want a defined number of ids returned in an $ids variable u can use the following code

<?php

$i              = 0;
$number_of_ids = 4;
$id_prefix  = "303.L";
$ids            = array();

while($i < $number_of_ids){
    $ids[] = $id_prefix . (++$i); // adds prefix and number to array ids.
}

var_dump($ids);
// will output '303.L1', '303.L2', '303.L3', '303.L4'
?>

I'm a bit confused because you say "without write it manually". But I think I have a solution:

$ids = array('303.L1', '303.L2', '303.L3', '303.L4');
$i = 0;
while($i <= count($ids)){

    ++$i;
    //Adding a new item to that array
    $ids[] = "303.L" . $i;
}

This would increment just that LAST number, starting at zero. If you wanted to continue where you left off, that'd be simple too. Just take $i = 0; and replace with:

//Grab last item in array
$current_index = $ids[count($ids) - 1];
//Separates the string (i.e. '303.L1') into an array of ['303', '1']
$exploded_id = explode('.L', $current_index);
//Then we just grab the second item in the array (index 1)
$i = $exploded_id[1];

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