Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php assigning multiple strings to a single variable

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?

like image 896
Norman Avatar asked Oct 14 '25 10:10

Norman


2 Answers

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);
like image 170
Marcelo Pascual Avatar answered Oct 17 '25 00:10

Marcelo Pascual


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

$names = array('John', 'Paul', 'Ringo');
$myStr = implode("<br>", $array);
echo $myStr;
like image 34
pita Avatar answered Oct 16 '25 23:10

pita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!