I have several cck image fields. Each field has a consecutive name, for example:

field_photos_1, field_photos_2, field_photos_3, field_photos_4 ... until 20

So my question is: How to call the image fields in a loop?

for example (pseudocode:)

for($i = 0; $i >= 20; $i++){
$cckname = 'field_photos_'.$i; //$cckname is changing the image field name, then...
echo "<img src='/".$node->$cckname[0]['filepath']."'";

The question in a general way could be: how to use dynamic names to call fields?


You can't access an array directly from a variable variable class property.

You have two options:

for($i = 0; $i >= 20; $i++){
  $cckname = 'field_photos_' . $i;
  $cckfield = $node->$cckname;
  echo "<img src='/" . $cckfield[0]['filepath'] . "'";

Or typecast the node object as an array:

for($i = 0; $i >= 20; $i++){
  $cckname = 'field_photos_' . $i;
  $node_array = (array) $node;
  echo "<img src='/" . $node_array[$cckname][0]['filepath'] . "'";
  • the two snippets do their job, thanks! and thanks for your explanation about variable variables – cigotete Aug 16 '11 at 14:23

You use curly braces {} to delimit the variable inside your reference, as

for($i = 0; $i >= 20; $i++) {
  $cckname = 'field_photos_' . $i; //$cckname is changing the image field name, then...
  echo "<img src='/" . $node->{$cckname}[0]['filepath'] . "'";

This syntax is used in many places in Drupal core, see for example hook_field_prepare_translation.

  • I thought the same thing but I tried $node->${$cckname}[0] which, in hindsight, is obviously the wrong syntax. d'oh – rocketeerbkw Aug 16 '11 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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