1

I've been getting the following php notice:

Notice: Undefined offset: 9 in include() (line 89 of node--name.tpl.php).

Here's the code:

<?php
// loops through array to print out addendum pdf's.
for ($i = 0; $i < 10; $i++) {
  $variable2 = "../sites/default/files/" . $node->field_addendum['und'][$i]['filename'];
  $variable1 = $node->field_addendum['und'][$i]['filename'];
  if (isset($variable1)) {
    $result = $i + 1;
    echo "<a href='$variable2' target='_blank'>$result&nbsp&nbsp&nbsp</a>";}
  else {}
}
?>

The field_addendum is a "file" field type from a custom content type. I understand why I'm getting the notice: if the node only has 3 addendums, once the loop gets to $node->field_addendum['und'][3]['filename'] and onwards, there is nothing in the array.

Is there a way to get the number of files without having to loop through the array first?

0

There are a few different ways to do the loop, personally I'd use a foreach statement. You can also compress your code a fair bit and make use of some API calls:

$options = array('attributes' => array('target' => '_blank'));
foreach (field_get_items('node', $node, 'field_addendum') as $index => $file) {
  echo l(($index + 1) . '&nbsp;&nbsp;&nbsp;', file_create_url($file['uri']), $options);
}

You could also use count($node->field_addendum['und']) to get the number of elements in the array if you want, but I think the above is a bit simpler.

Reference for API functions:

  • field_get_items()

    Returns the field items in the language they currently would be displayed.

  • l()

    Formats an internal or external URL link as an HTML anchor tag.

  • file_create_url()

    Create the download path to a file.

1
  • Thanks Clive. Still working my way through the api, so this was very useful. Worked perfectly.
    – coreyc
    Apr 25 '12 at 19:46
1

You can try to check if array element exist before assigment, and only if so, assign it, an this way avoid undefined offset:

  if (isset($node->field_addendum['und'][$i]['filename'])) {
     $variable1 = $node->field_addendum['und'][$i]['filename'];
    }

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.