Make your PHP functions more powerful
Here's a simple trick I've been using lately when working on Drupal functions that I may need to run on multiple nodes. Instead of writing functions that operate on a single value, allow an array to be passed instead. You'll find the function more useful in the future.
Take this function as an example. It returns an array of a node's taxonomy terms from the given vocabulary.
function get_terms($node, $vid) {
$tids = array();
foreach($node->taxonomy as $tid => $term) {
if($term->vid == $vid) {
$tids[$tid] = $term;
}
}
return $tids;
}Sure, that's a nice function. However, it can definitely be more powerful with a few extra lines of code. By converting both arguments to arrays and wrapping the original code in a foreach loop, the function now returns the union of all terms belonging to an array of nodes across multiple vocabularies. Also, any existing calls to the original function will still work fine.
function get_terms($nodes, $vids) {
if(!is_array($nodes)) $nodes = array($nodes);
if(!is_array($vids)) $vids = array($vids);
$tids = array();
foreach($nodes as $node) {
foreach($node->taxonomy as $tid => $term) {
if(in_array($term->vid, $vids)) {
$tids[$tid] = $term;
}
}
}
return $tids;
}