Skip to content

Instantly share code, notes, and snippets.

@gthuo
Last active January 2, 2019 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gthuo/b1a8f763c1fe9f406cb804a5e9592c78 to your computer and use it in GitHub Desktop.
Save gthuo/b1a8f763c1fe9f406cb804a5e9592c78 to your computer and use it in GitHub Desktop.
Automatically Pluralize Nouns in Laravel
<?php
// this function will return the plural or singular depending on the integer passed
//eg if $count=1 and $noun="post", it will echo 1 post..if $count!=1, it will echo X posts
/**
*@param count - Can be an integer, or a collection (which we use count() to know size) to know whether it is plural or singular
*@param noun - the noun to pluralize or sigularize
*@param return - to determine either to return it (eg when used in a controller) or echo it (default - eg used in a blade template)
*@param return_noun_only - when you only need the noun, and not the numeric part of it
*/
function autoPlural($count,$noun=null,$return = false,$return_noun_only=false)
{
// count can also be an array
if($count instanceof Illuminate\Database\Eloquent\Collection)
{
$count = $count->count();
}
elseif(is_array($count))
{
$count = sizeof($count);
}
$pluralized = ($count==1?str_singular($noun):str_plural($noun));
$output = $count.' '.$pluralized;
if($return)
return $return_noun_only?$pluralized:$output;
else
echo $return_noun_only?$pluralized:$output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment