I have the following code:

print $node->field_carousel_1[0]['filepath'];

What I would like to do is changing the 1, and use a variable instead.

Do you have any idea how I would be able to do this?

What I am aiming for is using a variable to create a looping function to print "field_carousel_1," "field_carousel_2," "field_carousel_3," etc.

  • This is not a Drupal question, but rather a PHP question. Drupal Answers is for questions specific for Drupal; in this case, the answer is not different if it would be asked about Wordpress, or plain PHP code.
    – apaderno
    Jan 26, 2012 at 14:35
  • Ok, i will post this on stackoverflow.
    – Sam Warren
    Jan 26, 2012 at 14:37
  • Check there isn't already a similar question, first. It is probable somebody already asked a similar question, and the answer is a feature present in PHP.
    – apaderno
    Jan 26, 2012 at 14:39
  • 1
    I'm afraid I still have to disagree. Sam is dealing with fields, and there may very well have been field API functions for his use case. You don't know unless you ask.
    – Chapabu
    Jan 26, 2012 at 15:36
  • 1
    I said there MIGHT have been, not there WAS...
    – Chapabu
    Jan 27, 2012 at 11:28

1 Answer 1


You can just change the 1 to your particular variable in the loop.


foreach ($values as $k => $v) {
  print $node->field_carousel_ . $v . [0]['filepath'];

That should output the values you need.

  • Thanks for replying, i actually get a syntax error on the print line there, any ideas why?
    – Sam Warren
    Jan 26, 2012 at 14:45
  • I've edited my answer...try it now, it's only really an example and you may have to modify it for your use case. It also may be slightly wrong as I'm on my phone at the moment ;-)
    – Chapabu
    Jan 26, 2012 at 14:55
  • It doesn't work, as PHP will try to access $node->field_carousel_, convert it to a string, and concatenate it with $v. It should also return you a syntax error.
    – apaderno
    Jan 26, 2012 at 21:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.