3

Is there a cleaner way to assign multiple strings to a single variable in php?

I current do like this

<?php
$myStr = '';

$myStr .= 'John';
$myStr .= '<br>';
$myStr .= 'Paul';
$myStr .= '<br>';
$myStr .= 'Ringo';

echo $myStr;
?>

I also use HEREDOC. But are there other ways?

BlitZ
  • 11,836
  • 3
  • 49
  • 64
Norman
  • 5,961
  • 21
  • 81
  • 131

2 Answers2

4

If you have to concatenate lot of data, it may be a good idea to use arrays. It's cleaner (not necessarily more memory efficient).

$items = array('Hello', 'How', 'Are', 'You?');
echo implode(' ', $items);
Marcelo Pascual
  • 811
  • 8
  • 20
3

It can be done by array and implode() like below

$names = array('John', 'Paul', 'Ringo');
$myStr = implode("<br>", $array);
echo $myStr;
Luke Mills
  • 1,596
  • 10
  • 18
pita
  • 108
  • 5