I have a string such as the following:

$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2;

My understanding of PHP is that the double-quotes in the second line will cause $s1 to be evaluated within the string, and the output will be

Apples are great

However, what if I wanted to keep $s2 as a "template" where I change $s1's value and then re-evaluate it to get a new string? Is something like this possible? For example:

$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2 . "\n";

$s1 = "Bananas";
$s3 = "$s2";
echo $s3 . "\n";

I find that the output for the following is:

Apples are great 
Apples are great

What I am hoping to get is more like:

Apples are great 
Bananas are great

Is such a thing possible with PHP where I can keep the "template" string the same, change the input variables, and then reevaluate to a new string? Or is this not possible with PHP?

share|improve this question
1  
Not sure if you would find this satisfactory, but you could use sprintf("%s are great", "Apples"); – mobius Jun 27 '12 at 7:35
using a function is advisable. – Back in a Flash Jun 27 '12 at 7:36

4 Answers

up vote 3 down vote accepted

Here you go: http://php.net/manual/en/function.sprintf.php

share|improve this answer

Well, you could do something like this: (just a quick mashup).

$template = "{key} are great";
$s1 = "Apples";
$s2 = "Bananas";

echo str_replace('{key}',$s1,$template) . "\n";
echo str_replace('{key}',$s2,$template) . "\n";
share|improve this answer

You can try use anonymous function (closure) for similar result: (only above PHP 5.3!)

$s1 = function($a) { 
    return $a . ' are great';
};

echo $s1('Apples');
echo $s1('Bananas');
share|improve this answer

You can also use reference passing (though it is much more commonly used in functions when you want the original modified):

<?php

$s4 = " are great";
$s1 = "Apples";
$s2 = &$s1;

echo $s2.$s4;

$s1 = "Bananas";
$s3 = $s2;
echo $s3.$s4;

?>

Output:

Apples are great
Bananas are great 
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.