clusterBuddy clusterBuddy - 2 months ago 8
PHP Question

PHP loop isn't working, what am I doing wrong?

I am building a function that would receive 2 params, a string and a number.
it would basically print the first letters $n of $s.


  • I need to run a loop, please don't advise other non looping methods.

  • And yes, I need to keep the loop true throughout the function, it's suppose to close when the
    if
    is met.



For some reason the loop isn't closing, even though there's a
return
in the
if
condition that is being met when
$stringCounter
equals
$n
(=10 in this example.)

function printCounter($s, $n)
{
$stringCaller = '';
$stringCounter = strlen($stringCaller);
while (1) {
$stringCaller .= $s;
if ($stringCounter == $n) {
return $stringCaller;
}
}
}

printCounter('aba', '10');

Answer

On my oppinion, TS is searching next approach:

function printCounter($s, $n)
{
    $result = '';
    $str_lenght = strlen($s);
    if(!$str_lenght) {
        return $result;
    }
    while (true) {
        $result .= $s;
        $result_lenght = strlen($result);
        if($result_lenght/$str_lenght >= $n) {
            return $result_lenght;
        }
    }
}

echo printCounter('aba', '10');
exit;