Reputation: 25
I've recently come across a bit of a problem about concatenating two string almost identically, but one would have more text than the other. Here is what I want to achieve and tried :
$var1 = $var2 = "the sky is ";
$var1 .= "grey and ";
$var1 .= $var2 .= "blue";
Obviously this will not work but the desired result is :
$var 1 : "the sky is grey and blue"
$var 2 : "the sky is blue"
Another operation wouldn't be much here but it's more about knowing if it is possible.
I could make a third temporary var but I was wondering if i could avoid it, other solutions would have been to have only 1 variable and remove with substring operations.
Upvotes: 0
Views: 283
Reputation: 2459
@janmyszkier approach is cleaner but there are many ways to stick around just saw your word complicated so i did this for you what was really happening behind the scene
$text= ["the sky is ","grey and "];
list($var,$var2) = $text;
echo addSuffix('blue',$var);
echo addSuffix('blue',$var2);
function addSuffix($suffix,$value) {
return $value.$suffix;
}
Upvotes: 1
Reputation: 2744
and more complicated variant:
$var1 = $var2 = "the sky is ";
$var1 .= "grey and ";
list($var1,$var2) = array_map(function($var){
return $var .= 'blue';
},[$var1,$var2]);
Upvotes: 1