Code Snippet
Variable Variables
<?php
$var1 = 'nameOfVariable';
$nameOfVariable = 'This is the value I want!';
echo $$var1;
?>
<?php
$var1 = 'nameOfVariable';
$nameOfVariable = 'This is the value I want!';
echo $$var1;
?>
Mind you can also do that with more $s:
And you can use curly brackets:
Mind you can also do that with more $s:
And you can use curly brackets:
no
Wow! I never even knew about this. Might be a pretty great asset in the future.
how? ^
I would like to ask a question, How to show variable in between the text.
E.g., I have
“var1 = $_POST['username'];”
I want to show it something like this,
“Hello [username]“.
How to do it?
I tried this but it didn’t work,
“echo Hello $var1;”
Please help me regarding this.
$var1=$_POST’username’];
echo “Hello [" . $var1 . "]“;
Try like this
$var=$_POST['username'];
echo ‘Hello['.$var.']‘;
If you need to create variables from an array there are two options.
The first uses php extract()
The second options which will give you more control is php list()
this is really bad practice and with proper code you should not need that mutation of code.
also, don’t directly output $_POST/$_GET or $_REQUEST content without using htmlentities() around it, as your site might be vulnerable to cross-site-scripting and other injections.
Hmmm, I’m probably just a little dense, but could you give an example of when this technique would be useful?
Hey Chris!
Just yesterday I found this in a MVC tutorial. There was the “Template.php” with the content ….
Now, if you want to fill this template you could use …
The variables
$header,$contentand$footer, called by the Template.php are provided by the foreach loop. When the Template.php is included, the variables “created” in the foreach loop are still accessable and therefore the HTML output is …Although I think this is “dirty” code somehow, it is an example of using variable variables.
Sorry for the bad code! Of course it is
</div>and not<div/>and i screwed up the html special entities for the assign operator => .I guess the posting-tip to turn all less-than signs in html special entities was for less-than signs only. My fault!
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.