Reputation: 33
how to combine variables with string and generate value
<?php
$bun1="home";
$x="1";
$h= "$"."bun".$x;
echo $h;
?>
I want print $bun1 with result home, but "1" in $bun1 be variable $x
Upvotes: 2
Views: 67
Reputation: 9583
Take a look, You just need to combine them so that you can make the variable name and then use the $
before that name to make it is a PHP variable.
$bun1 = "home";
$x = "1";
$h = ${"bun".$x};
echo $h;
You can also do the same thing like this way--
$bun1 = "home";
$x = "1";
$h = "bun".$x;
echo $$h; // this is called variable of variable. In `$h` you have only the 'bun1' and when you use a `$` before it it will be the `$bun1` and the value is `home`.
Upvotes: 3
Reputation: 30283
What you're trying to do is called variable variables.
PHP.net has a whole page on it.
<?php
$bun1="home";
$x="1";
$h= ${"bun".$x};
echo $h;
?>
Thing is though, from a design standpoint, you're almost always doing it wrong if you're using variable variables. Use arrays instead:
<?php
$bun[1] = "home";
$x=1;
$h= $bun[$x];
echo $h;
?>
If you're just trying to learn, then okay, have at it.
Upvotes: 7