PenAndPapers PenAndPapers -3 years ago 47
PHP Question

PHP Convert string to array and group by value

Im stuck in solving this, given a string like WWLLWWWLWLLL I want to group it into array so the output should be

[
0 => 'WW',
1 => 'LL',
2 => 'WWW',
3 => 'L',
4 => 'W',
5 => 'LLL',
]


Here is what I have started and I'm stuck what's the next step

$str = 'WWLLWWWLWLLL';
str_split($str);

Answer Source

Bit messy, but it does the job:

$str = 'WWLLWWWLWLLL';
$str = str_split($str);
foreach($str as $k => &$v) {
    $c = 1;
    while(isset($str[$k + $c]) && $str[$k + $c] == $v[0]) {
        $v .= $str[$k + $c];
        unset($str[$k + $c]);
        $c++;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download