Skip to content

Instantly share code, notes, and snippets.

@bluefuton
Created November 22, 2010 17:39
Show Gist options
  • Save bluefuton/710316 to your computer and use it in GitHub Desktop.
Save bluefuton/710316 to your computer and use it in GitHub Desktop.
Simple implementation of Rails' .to_sentence for PHP
<?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;
}
}
@crishoj
Copy link

crishoj commented Jul 14, 2016

This is actually buggy:
$array[($count - 1)]

Should be $count - 2 or simply end($array)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment