RSS

[php][tip] How to manage variable variable name?

29 Jun

While handling html form, sometimes one need to have dynamic field names and will do it with string concatenation with the respective variable but the issue was there while handling the form action.
Following is the code chunk which explains it well how to use variable variable names in php:

<h2>Enter Marks</h2>
<form name=”frm” id=”frm” method=”post” action=””>
<?php
$subject = array(“Eng”,”Urdu”,”Maths”);
for($i=0 ; $i<count($subject) ; $i++)
{
print “<p>”;
print “<label>”.$subject[$i].”</label>”;
$value = “”;
if(isset($_POST[‘subject_’.$subject[$i]]))
$value = $_POST[‘subject_’.$subject[$i]];
print “<input type=’text’ name=’subject_”.$subject[$i].”‘ id=’subject_”.$subject[$i].”‘ value=$value >”;
print “</p>”;
}
?>
<input type=”submit” />
</form>

<?php
$subject = array(“Eng”,”Urdu”,”Maths”);
if(count($_POST)>0)
{
print “<h2>Form Values</h2>”;
extract($_POST);
for($i=0 ; $i<count($subject) ; $i++)
{
print “<p>”;
print “<strong>”.$subject[$i].”:</strong>”;
print ${‘subject_’.$subject[$i]};
print “</p>”;
}
}
?>

Thus ${‘string’.$variable} is the right way to access variable variable name 🙂

Advertisements
 
Leave a comment

Posted by on June 29, 2012 in php

 

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: