Martin
Martin

Reputation: 22760

PHP append same string to multiple other strings in one line?

Appending to a single string is easy:

$string = "saucy";
$output = " you smell ". $string;
print $output;
// you smell saucy.

PHP also has a easy way of setting multiple values at once:

$aa = $bb = $cc = [];

But what if I want to append a string to multiple strings simultaneously?

For example:

$aa['horses'] = "trolls!";
$stringSomething = "This is better: ";
$stringElse = "This is less worse : ";

foreach($aa as $bb){
   $stringSomething .= $stringElse .= $bb; // THIS line
}

print $stringSomething;
print $stringElse;

This outputs:

This is better: This is less worse : trolls!
This is less worse : trolls!

What I am curious about is if you can have an output like this:

This is better: trolls!
This is less worse : trolls!

Currently all I can see is:

foreach($aa as $bb){
   $stringSomething .= $bb;
   $stringElse .= $bb; 
   $stringEntirely .= $bb;
   // .... 

}

Is there a way of wrapping this all up into a single line of appending the same value to multiple strings at once?

NOTE

The question here is NOT "How can I do this on an array", it is asking if there was a shorthand way of doing this with variables, as is possible with initial variable setting ( ie $a = $b = $c = 67;).

Upvotes: 0

Views: 704

Answers (4)

Martin
Martin

Reputation: 22760

There is currently no syntax of any specific shorthand to do this on pure variables.

There are various ways this can be done with array values and looping but this would involve adding code lines to the script and mitigate the intention to DRY down the original code.

Upvotes: 0

サスッガン
サスッガン

Reputation: 41

You can make it by using dynamic variable and an array with the name of your variables: dynamic variables

<?php

$aa = [];
$aa['horses'] = "trolls!";
$name1 = "smth";
$name2 = "smthelse";
$strings = ["name1", "name2"];

foreach($aa as $bb){
    foreach ($strings as $string) {
        $$string .= $bb;
    }
}

Upvotes: 1

yolenoyer
yolenoyer

Reputation: 9445

You can use array_map() by passing references to it:

<?php

$suffix = "trolls!";
$string1 = "This is better: ";
$string2 = "This is less worse : ";

array_map(fn(&$s) => $s .= $suffix, [&$string1, &$string2]);

echo "$string1\n";
echo "$string2\n";

Upvotes: 0

Gerard de Visser
Gerard de Visser

Reputation: 8050

The way to go would be to have these strings in an array and process like this:

<?php

$aa = [];
$aa['horses'] = "trolls!";
$strings = ["This is better: ", "This is less worse : "];

foreach($aa as $bb){
    foreach ($strings as &$string) {
        $string .= $bb;
    }
}

Upvotes: 1

Related Questions