"Conjunction" View Helper for Zend Framework
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)
// In a controller
$this->view->fruits = array(
'apples',
'bananas',
'oranges',
'lemons'
);
// In view script
<p><?= $this->conjunction($fruits) ?>
// Outputs "<p>apples, bananas, oranges and lemons</p>"
<p><?= $this->conjunction($fruits, 'or') ?>
// Outputs "<p>apples, bananas, oranges or lemons</p>"
Source
<?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}";
}
}
