2

I need to append a value to two variables.

$a = "String A";
$b = "String B";

...

$a .= " more";
$b .= " more";

Is there a shorter way to get this work?

$a .= $b .= " more"; is not doing what I want.

Thanks in Advance, Matty

3
  • 2
    The way you are doing is okay. And both the variable holds different values. Commented Feb 12, 2015 at 10:36
  • 1
    For two or three vars that's ok. If you have more, consider making a function. Commented Feb 12, 2015 at 10:39
  • You can't do that, with this, $a="String AString B more" and $b="String B more" is there is few of var to assign, make it like your first idea, else, just create a function to assign value. Commented Feb 12, 2015 at 10:42

1 Answer 1

4

Not really.

$a .= $b .= " more";

Is equivalent to:

$b .= " more";
$a .= $b;

The best way is to write:

$a .= " more";
$b .= " more";

Or (if you have a lot of them) use array with some functions:

#1 - array_map approach

function addMore(&$vars) {
    $var .= " more";
}
$array = [$a, $b];
$array = array_map('addMore',$array);

#2 - classic approach:

$array = array($a, $b);
foreach ($array_before as &$var) {
    $var .= " more";
}
Sign up to request clarification or add additional context in comments.

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.