0

I'm expecting this to print from "Count 1" to "Count 9". But the $str variable is not updating inside the while loop. It just prints "Count 1" nine times. In my use-case it's not possible to initiate $str inside the while loop therefore I'm looking for a dynamic update of the $str var inside the while loop.

    $p   = 1;
    $str = "Count {$p}";
    while ( $p < 10 ) {
        $p++;
        echo  $str . PHP_EOL;
    }
2
  • "In my use-case it's not possible to initiate $str inside the while loop" Please tell us more about your use case. If nothing else, how about doing a separate loop which initializes an array of strings, then use your while() loop to echo out those strings? Commented Mar 9, 2021 at 6:15
  • You could for example put a placeholder in $str, and then use sprintf to get that substituted with the current value of $p inside the loop … Commented Mar 9, 2021 at 7:50

2 Answers 2

2

You need to update your $str variable each loop.

$p = 1;

while ( $p < 10 ) {
    $str = "Count {$p}";
    echo  $str . PHP_EOL;
    $p++;
}
Sign up to request clarification or add additional context in comments.

Comments

0

As you mentioned you cant initiate $str inside your loop you can simply perform some concatenation to serve your purpose-

$p   = 1;
$str = "Count " ;
while ( $p < 10 ) {
    echo  $str . $p . PHP_EOL;
    $p++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.