Search code examples
phpstringloopsrepeatdelimited

Insert delimiter between each character in a string and repeat each letter using an increasing counter


I just want my loop to run, but when I try to do it, it fails. It has to increment each letter by an increasing amount based on how many iterations have occurred while looping, but it doesn't take any new letters at all.

Why is this happening and what is the reason? In C++, such code would work.

function accum('ZpglnRxqenU') {
    // your code
    $result = '';
    $letters_result = '';
    $letter_original = '';
    $num_if_str = strlen($s);
    $j = 0;
    for ( $i=0; $i <= $num_if_str; $i++ )
    {
        $letter_original = substr($s, $i, $i+1);
        $j = 0;
        while ($j == $i)
        {
            $letters_result = $letters_result . $letter_original;
            $j++;
        }
        if ($i != strlen($s))
        {
            $letters_result = $letters_result . '-';
        }

    }
    return $letters_result;
}

It returns: Z-----------

Expected:

Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu

Solution

  • There are a number of problems here:

    • you're using $s but never initialise it
    • Your call to substr() uses an incorrect value for the length of substring to return
    • you're inner loop only runs while $i = $j, but you initialise $j to 0 so it will only run when $i is zero, i.e. for the first letter of the string.

    There is a simpler way to do this. In PHP you can address individual characters in a string as if they were array elements, so no need for substr()

    Further, you can use str_repeat() to generate the repeating strings, and if you store the expanded strings in an array you can join them all with implode().

    Lastly, combining ucwords() and strtolower() returns the required case.

    Putting it all together we get

    <?php
    
    $str = "ZpglnRxqenU";
    $output = [];
    for ($i = 0;$i<strlen($str);$i++) {
        $output[] = str_repeat($str[$i], $i+1);
    }
    $output = ucwords(strtolower(implode('-',$output)),"-");
    
    echo $output;   // Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu
    

    Demo:https://3v4l.org/OoukZ