I am trying to make string serial comma from array. Here is the code I use:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
But the results I get:
I eat satay, orange, rambutan
Cannot:
I eat satay, orange, and rambutan
Yet!
So, I made my own function:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
// Reverse array
$ariBlk=array_reverse($ari,false);
foreach($ariBlk as $no=>$c){
if($no>=(count($ariBlk)-1)){
$rturn[]=$c.$delimiter;
}else{
$rturn[]=($no==0)?
$konj.$c
: $space.$c.$delimiter;
};
};
// Reverse array
// to original
$rturn=array_reverse($rturn,false);
$rturn=implode($rturn);
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Thus:
<?php
$eat = array_to_serial_comma(array('satay','orange','rambutan'));
echo "I eat $eat";
?>
Result:
I eat satay, orange, and rambutan
Is there a more efficient way, using a native PHP function maybe?
Edit:
Based on code from @Mash, I modifying the code that might be useful:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
$akr = array_pop($ari);
$rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr;
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
implode(" and ",array(implode(', ', $array),$last));
? – Thibault Aug 13 '13 at 12:37