• 13
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Add commas to items and with “and” near the end in PHP

I want to add a comma to every item except the last one. The last one must have "and".

Item 1, Item 2 and Item 3

But items can be from 1 +

So if one item:

Item 1

If two items:

Item 1 and Item 2

If three items:

Item 1, Item 2 and Item 3

If four items:

Item 1, Item 2, Item 3 and Item 4

etc, etc.

    • How predictable is the formatting? Obviously, you can'd just split items at every space character. Are they all called /[Ii]tem [0-9]+/ ? You wouldn't want "Item, 1, Item, 2, Item and 3". So ... is our input a string, or an array?

minitech's solution on the outset is elegant, except for one small issue, his output will result in:

var_dump(makeList(array('a', 'b', 'c'))); //Outputs a, b and c

But the proper formatting of this list (up for debate) should be; a, b, and c. With his implementation the next to last attribute will never have ',' appended to it, because the array slice is treating it as the last element of the array, when it is passed to implode().

Here is an implementation I had, and properly (again, up for debate) formats the list:

class Array_Package
{
    public static function toList(array $array, $conjunction = null)
    {
        if (is_null($conjunction)) {
            return implode(', ', $array);
        }

        $arrayCount = count($array);

        switch ($arrayCount) {

            case 1:
                return $array[0];
                break;

            case 2:
                return $array[0] . ' ' . $conjunction . ' ' . $array[1];
        }

        // 0-index array, so minus one from count to access the
        //  last element of the array directly, and prepend with
        //  conjunction
        $array[($arrayCount - 1)] = $conjunction . ' ' . end($array);

        // Now we can let implode naturally wrap elements with ','
        //  Space is important after the comma, so the list isn't scrunched up
        return implode(', ', $array);
    }
}

// You can make the following calls

// Minitech's function
var_dump(makeList(array('a', 'b', 'c'))); 
// string(10) "a, b and c"

var_dump(Array_Package::toList(array('a', 'b', 'c')));
// string(7) "a, b, c"

var_dump(Array_Package::toList(array('a', 'b', 'c'), 'and'));
string(11) "a, b, and c"

var_dump(Array_Package::toList(array('a', 'b', 'c'), 'or'));
string(10) "a, b, or c"

Nothing against the other solution, just wanted to raise this point.

  • 2
Reply Report

Here's a variant that has an option to support the controversial Oxford Comma and takes a parameter for the conjunction (and/or). Note the extra check for two items; not even Oxford supporters use a comma in this case.

function conjoinList($items, $conjunction='and', $oxford=false) {
    $count = count($items);

    if ($count === 0){
        return '';
    } elseif ($count === 1){
        return $items[0];
    } elseif ($oxford && ($count === 2)){
        $oxford = false;
    }

    return implode(', ', array_slice($items, 0, -1)) . ($oxford? ', ': ' ') . $conjunction . ' ' . end($items);
}
  • 1
Reply Report

You can do it like this:

$items = array("Item 1", "Item 2", "Item 3", "Item 4");

$item = glueItems($items);

function glueItems($items) {
    if (count($items) == 1) {
        $item = implode(", ", $items);
    } elseif (count($items) > 1)  {
        $last_item = array_pop($items);
        $item = implode(", ", $items) . ' and ' . $last_item;
    } else {
        $item = '';
    }
    return $item;
}
echo $item;
  • 1
Reply Report

Well if it is an array just use implode(...)

Example:

$items = array("Item 1", "Item 2", "Item 3", "Item 4");
$items[count($items) - 1] = "and " . $items[count($items) - 1];
$items_string = implode(", ", $items);

echo $items_string;

Demo: http://codepad.viper-7.com/k7xISG

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions