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

后端 未结 6 702
名媛妹妹
名媛妹妹 2021-01-12 03:08

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 on

6条回答
  •  渐次进展
    2021-01-12 03:54

    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.

提交回复
热议问题