Search code examples
phpdrupaldrupal-7

How to assign field name dynamically in Drupal


I have Drupal 7 site. It has custom content type node which has 25+ fields of which 10 fields have very similar name.

In a scenario, I need to loop through n products & need to get the different fields values.

In order to avoid if-else chain, I am thinking to construct the field name dynamically in the following way.

function GetProduct($node,$a)
{
     $fieldName = "field_product_" . $a;
     print_r( $node->$fieldName[LANGUAGE_NONE][0]['value'] ); // not getting value

}

I am using php v 5.5.12

How to get the field value in this way?

Any help highly appreciated.


Solution

  • You just forgot braces :) Use $node->{$fieldName} instead of $node->$fieldName:

    print_r( $node->{$fieldName}[LANGUAGE_NONE][0]['value'] ); // works