Kofi
Kofi

Reputation: 15

Split a string into smaller strings and not arrays

need a little help with a small issue of string splitting.

I'm trying to split a serial number into two, do some calculations on the second half and join it back to the first half. My problem is the second half starts with two zeros and PHP removes the leading zeros.

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>";
}

Any help is greatly appreciated.

Upvotes: 0

Views: 119

Answers (3)

Steve
Steve

Reputation: 20469

If the string will always be 4 chars long, you can use str_pad

for ($num=1; $num < $unitsquantity[$key] ; $num++) {
  echo $number1 . str_pad($number2+$num, 4, '0', STR_PAD_LEFT);
}

Upvotes: 1

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

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.

Upvotes: 0

Pater SVK
Pater SVK

Reputation: 69

$info1 = 'nkw549blc003i00021';

$number1 = substr($info1, 0, -4);
$number2 = sprintf('%1$04d', substr($info1, -4, 4));

Upvotes: 1

Related Questions