I'm trying to split a serial number into two parts, do some calculations on the second half and join it back to the first half.
My problem is the second half string has leading zeros and after performing my arithmetic on the value, the leading zeros are lost.
I think keeping the variables as strings will keep the zeros but I can't seem to find a way to split the serial number into smaller strings, all the methods I try split them into an array. Here is a part of my code;
$info1 = nkw549blc003i00021; //this is the serial number.
I want to split $info1
into;
$number1 = nkw549blc003i0
$number2 = 0021
then use for loop
on $number2
like
$num = 1;
for ($num=1; $num < $unitsquantity[$key] ; $num++) {
$sum = $number2+$num;
$final=$number1.$sum;
echo "$final<br>";
}
Strings are array chars, so you can get each char of them by iterating through their length
define('SERIAL_NUM_LEN', 4);
$info1 = 'nkw549blc003i00021';
$number1 = ''; $number2 = '';
for ($i = 0; $i < strlen($info1)-SERIAL_NUM_LEN; $i++) {
$number1 .= $info1[$i];
}
for ($i = strlen($info1)-SERIAL_NUM_LEN; $i < strlen($info1); $i++) {
$number2 .= $info1[$i];
}
var_dump($number1, $number2);
Output:
string 'nkw549blc003i0' (length=14)
string '0021' (length=4)
This way you can skip whichever chars from the string you want if you want to build totally different string. Or add chars in the middle.