Note that there are some explanatory texts on larger screens.

plurals
  1. POSerial comma from array in PHP
    text
    copied!<p>I am trying to make string <a href="https://en.wikipedia.org/wiki/Serial_comma" rel="nofollow">serial comma</a> from array. Here is the code I use:</p> <pre><code>&lt;?php echo "I eat " . implode(', ',array('satay','orange','rambutan')); ?&gt; </code></pre> <p>But the results I get:</p> <pre><code>I eat satay, orange, rambutan </code></pre> <p>Cannot:</p> <pre><code>I eat satay, orange, and rambutan </code></pre> <p>Yet!</p> <p>So, I made my own function:</p> <pre><code>&lt;?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)&gt;2){ // Reverse array $ariBlk=array_reverse($ari,false); foreach($ariBlk as $no=&gt;$c){ if($no&gt;=(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 &gt;=2 then regular merger $rturn=implode($konj,$ari); }; // Return return $rturn; }; ?&gt; </code></pre> <p>Thus:</p> <pre><code>&lt;?php $eat = array_to_serial_comma(array('satay','orange','rambutan')); echo "I eat $eat"; ?&gt; </code></pre> <p>Result:</p> <pre><code>I eat satay, orange, and rambutan </code></pre> <p>Is there a more efficient way, using a native PHP function maybe?</p> <p><strong>Edit:</strong></p> <p>Based on code from @Mash, I modifying the code that might be useful:</p> <pre><code>&lt;?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)&gt;2){ $akr = array_pop($ari); $rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr; }else{ // If &gt;=2 then regular merger $rturn=implode($konj,$ari); }; // Return return $rturn; }; ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload