Is it possible to combine a variable and a string to a new variable and echo it?
I have the following string:
$string = '01001'
Trying something like:
$var = $_$string
Ultimately I want to end up with a var like $_01001
that I can print. So if I have a bunch of data like:
$_01001 = 'foo'; $_01002 = 'bar'; $_01003 = 'fooz'; $_01004 = 'barz';
So echo $_01001;
would produce foo
... thanks in advance.
Yes you can use. have a look on below example:
$_01001 = 'foo';
$_01002 = 'bar';
$string1 = '01001';
$string2 = '01002';
echo ${"_$string1"};
echo ${"_$string2"};
Output: foobar
mode detail available at Variable of variable
$string = '01001';
$vals = [
'01001' => 'foo',
'01002' => 'bar',
'01003' => 'fooz',
'01004' => 'barz',
];
echo $vals[$string]; // produces "foo"
Yah, I know, boring and lacking magic. But readable maintainable code is often boring and magicless. Variable variables voodoo does exist in PHP but will just distract future readers/maintainers (including yourself 1+ weeks from now) from what you're really trying to do in your logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.