How can I split a string with no delimiters, for example $a = '89111213';
, into an array of integers?
Desired result:
[8, 9, 11, 12, 13]
I generate that input number in a loop with concatenation like $a .= $somevariable;
.
Update:
As @therefromhere suggests in his comment, instead of concatenating the numbers into one string,put them in an array directly:
$a = array();
for(...) {
$a[] = $somevariable;
}
Here is something that works in a way.
Important:
Assumption: Numbers are concatenated in increasing order and start with a number < 10 :)
$str = "89111213";
$numbers = array();
$last = 0;
$n = '';
for($i = 0, $l = strlen($str);$i<$l;$i++) {
$n .= $str[$i];
if($n > $last || ($i == $l - 1)) {
$numbers[] = (int) $n;
$last = $n;
$n = '';
}
}
print_r($numbers);
prints
Array
(
[0] => 8
[1] => 9
[2] => 11
[3] => 12
[4] => 13
)
Although this might work to some extend, it will fail in a lot of cases. Therefore:
How do you obtain 89111213
? If you are generating it from the numbers 8,9,11, etc. you should generate something like 8,9,11,12,13
.