RSS

Monthly Archives: June 2012

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

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: , , , ,

 
%d bloggers like this: