note 52363 deleted from function.implode by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 13:15:59 +0000 |
| Subject: | note 52363 deleted from function.implode by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189718@lists.php.net to get a copy of this message | ||
Note Submitter: Andy Morris
----
Similar to a previous note, but this works for any length array, plus also works for arrays with key
strings instead of integer keys! I know it's not strictly an implode() example, but it concerns
what you might be considering using implode() to help you to do achieve...
<?php
// Return array as a comma separated list; final two elements separated
// by 'and' with an optional "Oxford" comma preceding the 'and'.
function english_list($array, $oxfordComma=0)
{
$optionalComma = ( $oxfordComma ) ? "," : "";
$str = "";
$size = count( $array );
$i = 0;
foreach ( $array as $item ) {
$str .= $item;
$i++;
if ( $i < $size - 1) $str .= ", ";
elseif ( $i == $size - 1) $str .= $optionalComma." and ";
}
return $str;
}
// test the comma separated list function
echo english_list( array(), 1 )."<br>";
echo english_list( array("foo"), 1 )."<br>";
echo english_list( array("foo", "bar"), 0 )."<br>";
echo english_list( array("a" => "foo", "b" => "bar",
"c" => "foobar"), 1 )."<br>";
echo english_list( array("foo", "bar", "foobar", "barfoo"),
0 )."<br>";
?>