Generating a PHP list with "and"
What's an efficient way to format an array in PHP as a list with commas and the word "and" before the last element?
$array = Array('a','b','c','d');
I want to开发者_运维百科 produce the string "a, b, c, and d"
I would modify the $array
in place to add the "and"
, and then join the parts with commas for output:
array_push($array, " and " . array_pop($array));
print join(", ", $array);
But you might as well just use array_pop
to separate the last entry, join the rest, and then append the "and" and last entry.
I suppose that should do it:
$array[ sizeof($array) - 1 ] = 'and ' . $array[ sizeof($array) - 1 ];
$list = implode(', ', $array);
There are a number of ways you could do it, here is one:
<?
$array = Array('a','b','c','d');
$string=implode(',',$array);
$nstring=substr_replace($string,' and ', -1, 0);
echo $nstring;
<?php
$array = Array('a','b','c','d');
$array[count($array)-1] = 'and '.$array[count($array)-1];
echo implode($array, ', ');
?>
http://codepad.org/7oeni6xv
Try:
function arrayEnum($array)
{
$string = '';
for (i = 0, $l = count($array); i < $l; ++i)
{
$string .= $array[$i];
if (i != ($l -1)) $string .= ', ';
if (i == ($l -2)) $string .= 'and '
}
}
$array = Array('a','b','c','d');
echo $array; // a, b, c, and d
$array = Array('one','two','three','four');
echo $array; // one, two, three and four
That function will work with any length of data.
精彩评论