function - Serial comma from array in PHP -
i trying make string serial comma array. here code use:
<?php echo "i eat " . implode(', ',array('satay','orange','rambutan')); ?>
but results get:
i eat satay, orange, rambutan
cannot:
i eat satay, orange, , rambutan
yet!
so, made own function:
<?php function array_to_serial_comma($ari,$konj=" , ",$delimiter=",",$space=" "){ // if not array, quit if(!is_array($ari)){ return false; }; $rturn=array(); // if more 2 // actions if(count($ari)>2){ // reverse array $ariblk=array_reverse($ari,false); foreach($ariblk $no=>$c){ if($no>=(count($ariblk)-1)){ $rturn[]=$c.$delimiter; }else{ $rturn[]=($no==0)? $konj.$c : $space.$c.$delimiter; }; }; // reverse array // original $rturn=array_reverse($rturn,false); $rturn=implode($rturn); }else{ // if >=2 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, , rambutan
is there more efficient way, using native php function maybe?
edit:
based on code @mash, modifying code might useful:
<?php function array_to_serial_comma($ari,$konj=" , ",$delimiter=",",$space=" "){ // if not array, quit if(!is_array($ari)){ return false; }; $rturn=array(); // if more 2 // actions if(count($ari)>2){ $akr = array_pop($ari); $rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr; }else{ // if >=2 regular merger $rturn=implode($konj,$ari); }; // return return $rturn; }; ?>
here's cleaner way:
<?php $array = array('satay','orange','rambutan'); $last = array_pop($array); echo "i eat " . implode(', ', $array) . ", , " . $last; ?>
array_pop()
takes last element out of array , assign $last
Comments
Post a Comment