0

hook_node_load($nodes, $types) in Drupal 7 takes two arrays as parameters. In the module I'm working on (Drupal 7 port from Drupal 6), just one node of one type is being loaded. I tried $node[0] to specify the first node in the array, but no joy. How do I get at the first node and the first type? There is only one object in each array.

4
  • array_shift Feb 23, 2015 at 3:54
  • You should take care with array_shift(), though, since it removes the item from the array. It shouldn't matter for this particular hook, but there are others that pass by reference.
    – Les Lim
    Feb 23, 2015 at 3:59
  • you could use $node = reset($nodes); as well
    – thumbson
    Feb 23, 2015 at 4:13
  • Thanks. So, it turns out that the node array is an array of objects. But I guess I still can use this. Feb 23, 2015 at 10:04

1 Answer 1

1

$nodes is keyed by the node ID, which you probably won't know in advance. Instead of directly trying to access the first node in the array, iterate over them with a foreach loop.

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $nid => $node) {
    if ($node->type == 'basic_page') {
      ...
    }
  }
}
1
  • I need to somehow identify the object that is the first node in the array of node objects. I think the reset() function will do that, won't it? Feb 23, 2015 at 10:05

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.