Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to concatenate a reference to string variable?

In the following snippet of PHP the $phrases needs to reflect the change made in $greeting. How can this be achieved?

$greeting = "Hello!";

$phrases = array('greeting' => $greeting . " Glad to see you.");
echo $phrases['greeting'];

Hello! Glad to see you.

$greeting = "How are you?";
echo $phrases['greeting'];

Hello! Glad to see you.

Note, that even after the value of $greeting variable changed, the array remained unchanged (which is normally an expected behavior, since the value of $greeting var is passed by value).

In order to make array to do change, I tried to use references to variables, but they don't seem to work with concatenation operator ..

Appreciate if anyone could suggest a quick solution to this..

like image 492
Ivan Balashov Avatar asked Dec 02 '25 04:12

Ivan Balashov


1 Answers

most common way to add placeholders to your strings would be printf()

$phrases = array('greeting' => "%s Glad to see you.");

$greeting = "Hello!";
printf($phrases['greeting'],$greeting);
$greeting = "How are you?";
printf($phrases['greeting'],$greeting);
like image 153
Your Common Sense Avatar answered Dec 03 '25 17:12

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!