Created
November 22, 2010 17:39
-
-
Save bluefuton/710316 to your computer and use it in GitHub Desktop.
Simple implementation of Rails' .to_sentence for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ArrayExtensions | |
{ | |
public function to_sentence($array) | |
{ | |
$count = count($array); | |
switch ($count) | |
{ | |
case 0: | |
$str = ''; | |
break; | |
case 1: | |
$str = $array[0]; | |
break; | |
case 2: | |
$str = $array[0].' and '.$array[1]; | |
break; | |
default: | |
$str = implode(', ', array_slice($array, 0, -1)).' and '.$array[($count - 1)]; | |
break; | |
} | |
return $str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is actually buggy:
$array[($count - 1)]
Should be
$count - 2
or simplyend($array)