I need to generate a set of number consist of Current Year, Current Month, and Incremental 4 digit with zero leading. with conditions:
- The last 4 digit number is increment from the last record on database.
example:
2020080023 -> last database record 2020080024 -> so this is will be the next record
- on beginning of month the last 4 digit reset to 0001.
example:
2020080023 -> last database record on end of month 2020090001 -> so this is will be the next record
this is what i have so far:
$currentYear = date('Y'); $currentMonth = date('m'); $last4Digits = '0001'; $formatedNumber = $currentYear.$currentMonth.$last4Digits;
Question how to increment the last 4 digit from last record and how to reset to 0001 on beginning of month?
Advertisement
Answer
The solution requires the last formatted ID and a little logic. If the last ID is in the current month, it only needs to be increased by 1. If this is not the case, the new month starts at 1.
function getId($lastId){ $curYm = (int)date('Ym'); $lastYm = (int)($lastId/10000); if($lastYm == $curYm) return ++$lastId; return $curYm * 10000 + 1; }
examples:
$id = 2020080007; $nextId = getId($id); //int(2020080008) $id = 2020070127; $nextId = getId($id); // int(2020080001)