EDIT: SOLVED
ORIGINAL POST:
I have a foreach loop which creates variables in the form of:
foreach ($fieldsarray as $field)
{
${$field} = $globalrow[$field];
}
This creates variables using array elements, like $firstname, $lastname, etc.
Now, since the values of these variables are fetched from the DB, I cannot use the variable names again in the same foreach. What I would like to do is to use this in the loop:
if(!empty($$field))
{
$r.$field='<tr><td width="50%">'.${$field}._label.': </td>
<td width="50%">'.${$field}.'</td></tr>';
}
Basically, this would generate table rows with data from DB, but only if the value of the variable is not empty.
My problem is: Since I have declared above that e.g. $firstname = 'John' - then the second part of the code does not work anymore, because I assume PHP does not transform the above snippet into
if(!empty($firstname))
but rather into
if(!empty(John))
How can I "force" PHP to again use the variable NAME rather than its value in this case?
Thank you for your help.
EDIT: OK, cheezeburgers suggestions worked and I think now it's working as intended. Thanks to all of you for your help.
EDIT 2: The table rows are output correctly on the screen, e.g.:
First Name: John
Last Name : Smith
but for some weird reason in the email confirmation the output is doubled:
First Name: John
Last Name : Smith
First Name: John
Last Name : Smith
In both cases I simply echo them with:
<?php echo $allrows ?>
where $allrows is in the foreach loop.
(I will post this part as a new question since this seems to be a new problem now)
PHP will work it out fine, just that you have missed the quote around _label
and probably that's being read as a constant.
Try this:
$$field='<tr><td width="50%">'.${$field}.'_label: </td>
<td width="50%">'.${$field}.'</td></tr>';
which gives the output as:
John_label: John
I would do that differently altogether, but to answer your question, try this:
extract($globalrow);
It creates variables in the current scope for every entry in the array going by the name of the respective key. So as long as there are no numeric keys, this should work instead of ${$field} = $globalrow[$field];
. Then just refer to the variables by actual name.