Magento, PHP, MySQL, AJAX, Zend, cPanel or OpenSource…
How to define dynamic variable in php?
If you need to define variable dynamically in php then this can be done easily.
Say, your variable name will be ‘dynamic_variable_name’
Generally we define php variable normally as $normal_variable; but in this case we would like to create dynamically.
Then we have to write something like following way:
$normal_variable = 'dynamic_variable_name';
${$normal_variable} = 'New dynamic variable created';
echo $dynamic_variable_name;
// prints New dynamic variable created.
To explain it better I am giving an instance which will be very helpful to develop PHP sites and reduce some hard work.
I have a form as given below:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> First Name : <input type="text" name="first_name"><br /> Last Name : <input type="text" name="last_name"><br /> <input type="submit" name="submit" value="Submit" > </form>
While you submit the form, capture all variables and values:
if(!empty($_POST)){
foreach($_POST as $variable => $key){
${$variable} = trim($key);
}
echo $first_name . ' ' . $last_name;
}
| This entry was posted by admin on September 6, 2010 at 1:17 pm, and is filed under General, PHP/MySQL. Follow any responses to this post through RSS 2.0. You can skip to the end and leave a response. Pinging is currently not allowed. |
about 4 months ago
Thanks for the share!
Nancy.R