Aidan's PHP Repository

A repository for PHP functions and classes ...

function.natural_list.php

Return an array as a natural list

  • Author: Aidan Lister <aidan@php.net>
  • Version: 1.0.0
  • Link: http://aidanlister.com/repos/v/function.natural_list.php
  • Views: 6810
  • Downloads: 1443

Source

Download this script <?php
/**
 * Return an array as a natural list
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.0.0
 * @link        http://aidanlister.com/repos/v/function.natural_list.php
 * @param       array    $array    The array
 */
function natural_list($array)
{
    $array = array_values($array);
    
    if (count($array) > 1) {
        $last = array_pop($array);
        $str = implode(', ', $array);
        $str .= ', and ' . $last;
    } elseif (count($array) === 1) {
        $str = $array[0];
    } else {
        return '';
    }
 
    return $str;
}
 
?>

Example

<pre>
<?php
require_once 'function.natural_list.php';
 
$items = array('banana', 'apple', 'carrot', 'donkey');
 
echo natural_list($items);
 
?>
</pre>

Output

banana, apple, carrot, and donkey

Comments

No comments.