0

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.

4
  • 6
    this is micro optimisation and a waste of time imho Commented Aug 29, 2018 at 9:28
  • to help you understand, the operations in your 3rd line are executed from right to left, first $var2 .= "blue" then $var1 .= (result of preceding) Commented Aug 29, 2018 at 9:30
  • 1
    @delboy1978uk Yes it kinda is, it doesn't serve much but just satisfy my curiosity ! Commented Aug 29, 2018 at 9:30
  • @Kaddath I'm aware it wouldn't work and understand this operation, as $var1 would get twice the beginning. Commented Aug 29, 2018 at 9:34

2 Answers 2

1

and more complicated variant:

$var1 = $var2 = "the sky is ";
$var1 .= "grey and ";
list($var1,$var2) = array_map(function($var){
    return $var .= 'blue';
},[$var1,$var2]);
Sign up to request clarification or add additional context in comments.

1 Comment

That's indeed complicated but it does the job ! thanks
1

@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;
}

1 Comment

Thanks ! It does explain the operations, even though the results are not the expected ones, but that wasn't the goal of your comment I believe ?

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.