I am trying to do something like htis
foreach ($_POST as $key => $value)
{
$newNode->field_$key['und'][0]['value'] = $value;
}
php complains of Parse error: syntax error, unexpected T_VARIABLE
I tried
foreach ($_POST as $key => $value)
{
$newNode->field_{$key}['und'][0]['value'] = $value;
}
But then key is output as an array. Not sure why.
Any tips?
The correct notation would be
$newNode->{"field_".$key}
that should work. But as @Furicane says, arrays are vastly better for this.
variable name (and also object property) cannot have $ in name.
To get this working, read about getters and setters with __get and __set
If I may suggest an alternative approach - which is to use an array. You shouldn't try to dynamically create variable names. For that purpose, good engineers from a long, long time ago in a year far far away invented an array.
So, to solve your problems from now and the whole eternity - rewrite your code to use:
$newNode->field[$key]['und'][0]['value'] = $value;
Try using a variable for the full property name.
foreach ($_POST as $key => $value)
{
$fieldName = "field_{$key}";
$newNode->{$fieldName}['und'][0]['value'] = $value;
}