Login with OpenID

"Conjunction" View Helper for the Zend Framework

Written by Hector Virgen
Published on June 3, 2009

Many times in dynamic web sites you will need to list items in a sentence, but if you don't know how many items there are then it can be tedious to join them with a conjunction. That's where the Conjunction view helper for the Zend Framework comes in. It accepts an array of items and joins them with commas except for the last item, which is prefixed with "and" or any other conjunction of your choice.

Usage (Within a View Script)

 
<?php
 
$fruits = array(
    'apples',
    'bananas',
    'oranges',
    'lemons'
);
 
echo $this->conjunction($fruits);
// Outputs "apples, bananas, oranges and lemons"
 
echo $this->conjunction($fruits, 'or');
// Outputs "apples, bananas, oranges or lemons"

Class: Virgen_View_Helper_Conjunction

 
<?php
 
/**
 * Uses a conjunction to join items in the English language as in the sentence:
 * 
 * "Red, blue and green are all colors."
 *
 */
class Virgen_View_Helper_Conjunction
{
    public function conjunction($items, $type = 'and')
    {
        // Return empty string if no items are in array
        if (count($items) == 0) return '';
        
        // Return first item if only 1 item
        if (count($items) == 1) return $items[0];
        
        // Build conjunction
        $last = array_pop($items);
        $first = implode(', ', $items);
        
        return "{$first} {$type} {$last}";
    }
}

4 Comments Post a comment!

  • July 08, 2009
    This is greate idea and this will be better if you can integrate the translator helper for the $type.
  • July 08, 2009
    That's a good idea. I haven't had a worked with Zend_Translate yet. Do you have any suggestions on how to implement that feature in this view helper?
  • July 08, 2009
    You can see Zend_View_Helper_HeadTitle class.
  • July 08, 2009
    Thanks! I'll check it out.

Post a Comment!

To protect against spam, please verify you are human.