I would like to declare a string containing a variable name in it, and then have php be able to identify that variable from within the string, like a javascript eval. Examples:
This code works, because the value of $value is what ends up in the string, not "$value".
$value="some value";
$str="the value is $value";
echo $str;
//the value is some value
But i would like this functionality:
$str2="the new value is $newValue";
$newValue="something new";
echo $str2;
//the new value is something new
Of course this does not work in php because $newValue did not exist when $str2 was assigned. Is there anyway for php to do this, to be able to get a variable name from a string, then fetch the value of that variable? It's sort of like a javascript eval I guess. Thanks for reading!
usage: i am constructing html blocks inside of a foreach loop. it loops thru an array, so the information inside of the loop is the key and value of each array element. I am writing a method for a form object that lets the user specify elements of an input block. some of those elements would like access to the key, and some would like access to the value. so for example
foreach($cars as $key=>$car)
{
echo "<input id='text$key' type='text' value='".$car["model"]."'><br>
\n<input value='choice$key' type='button' value='".$car["make"]."'>
<br><br>\n\n";
}
would yield something like
<input id="text0" type="text" value="Malibu"><br>
<input id="choice0" type="button" value="Chevy"><br><br>
<input id="text1" type="text" value="Escort"><br>
<input id="choice1" type="button" value="Ford"><br><br>
I want this to be generated on the fly, so say I have some method called makeCarForm, which takes a string as input, so lets say
function makeCarForm($formString)
{
foreach($cars as $key=>$car)
{
echo $formString;
}
}
and then my string
$theFormString="<input id='text$key' type='text' value='".$car["model"]."'><br>
\n<input value='choice$key' type='button' value='".$car["make"]."'>
<br><br>\n\n";
so I could call the function like
makeCarForm($theFormString);
and it would yield the same HTML output as above. Does this make sense? Am I going about this the wrong way?
sprintf()
– HAL9000 Jul 5 at 2:16