4

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?

9
  • 3
    whats wrong in this ? its perfectly fine Commented Jun 12, 2013 at 3:28
  • 1
    $myStr = 'John'.'<br>'.'Paul'.'<br>'.'Ringo'; Commented Jun 12, 2013 at 3:29
  • This simple example can be reduced to a one liner, but maybe you should provide more context to your question. Commented Jun 12, 2013 at 3:30
  • 1
    @Antony why not like $myStr = 'John <br> Paul <br> Ringo'; :P Commented Jun 12, 2013 at 3:30
  • 2
    cleaner is not always better way .... if i were you i would use string concatenation method Commented Jun 12, 2013 at 3:42

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

A memory consuming and slow idea.
at least it answer the question in not an ironic way
@NullPoiиteя Yes, sure. It depends on situation. There might be even a special class for OP's needs.
3

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

$names = array('John', 'Paul', 'Ringo');
$myStr = implode("<br>", $array);
echo $myStr;

1 Comment

2 DownVoter. Please, be more constructive. Supply downvotes with 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.