0

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?

4 Answers 4

8

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;
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Exactly. Arrays are already in copious use anyway, so adding another dimension wouldn't hurt.
This is not entirely true, as there are valid use-cases for dynamically accessing properties. Late static binding makes a host of well-built applications possible in php 5.3. Don't misconstrue this statement though; usually an array would be appropriate.
Also, if you are indexing that many things at once, you should probably think about what you are doing and add some classes as appropriate.
Thanks for the tip, unfortunately my hands are tied on this one as I am working with Drupal that uses this notation for fields, here is an example: timonweb.com/comment/4751
6

The correct notation would be

$newNode->{"field_".$key}

that should work. But as @Furicane says, arrays are vastly better for this.

1 Comment

Thanks, this is a winner. I will mark it as such when 4 minutes expired. :)
1

Try using a variable for the full property name.

foreach ($_POST as $key => $value)
{
    $fieldName = "field_{$key}";
    $newNode->{$fieldName}['und'][0]['value'] = $value;
}

1 Comment

Thanbks this is a winner as well. Pekka's solution was posted before this, so I will mark that as correct.
0

variable name (and also object property) cannot have $ in name.

To get this working, read about getters and setters with __get and __set

1 Comment

Thanks for the comment, will read up on this. Pekka's solution works so I went with that for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.