-1

How I can get $lorem_text as a new string $lorem_outside_text without changing $lorem_text?

for ($i = 0; $i <= 5; $i++) {
  $lorem_text = "lorem\n";
}

$lorem_outside_text = $lorem_text;

echo $lorem_outside_text;

Now result is: lorem

Result should be: lorem lorem lorem lorem lorem

  • What do you mean by `without changing $lorem_text`? – Devon Jul 30 '18 at 16:39
  • Do you want *both* variables to contain the text five times? It looks like that's what you've tried to do, but I'm not sure why you think copying a string would change the original. – iainn Jul 30 '18 at 16:40

5 Answers5

3

You may use concatenating assignment operator, Please try the following code:

$lorem_text .= "lorem\n";
$lorem_outside_text = '';

for ($i = 0; $i <= 5; $i++) {
  $lorem_outside_text .= $lorem_text;
}

echo $lorem_outside_text;
MyLibary
  • 1,687
  • 8
  • 17
3

With this piece of code you are overwriting your existing value every time.

for ($i = 0; $i <= 5; $i++) {
  $lorem_text = "lorem\n"; // this just overwrites $lorem_text value 6 times with same value
}

Instead try to concatenate it using . and also remove extra using of variables here $lorem_outside_text

$lorem_outside_text = ''; //intialize it as empty string
for ($i = 0; $i <= 5; $i++) {
  $lorem_outside_text .= "lorem\n";
}
echo $lorem_outside_text;

Pretty Neat:

<?php
echo str_repeat("lorem\n", 6);
?>

DEMO: https://3v4l.org/CIsCB

Always Sunny
  • 32,751
  • 7
  • 52
  • 86
2

You must append the text to the $lorem_text, not overwrite it. Type .= instead of =.

Personally, I'm usually adding text fragments to an array inside a loop, and then concatenate them using implode("\n", $lorem_parts).

Furgas
  • 2,692
  • 1
  • 17
  • 26
2

Just use str_repeat, that will repeat the string however many times you want.

str_repeat($lorem_text, 5);
user3783243
  • 5,098
  • 5
  • 16
  • 37
1

Another option is to create an array in the loop that you later implode.

for ($i = 0; $i <= 5; $i++) {
  $lorem_text[] = "lorem";
}



echo implode("\n", $lorem_text);

Implode takes an array and uses the glue to make it string.

Andreas
  • 23,304
  • 5
  • 28
  • 61