Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Plural strings based on the count in Laravel

Working with strings can prove to be tricky in some scenarios. For instance, when building a cart for an eCommerce website, you may need to show the string “item” in singular/plural form based on how many items are there in the cart.

You may resort to using it like so and be done with it. ⟶ “item(s)”

But luckily, if you’re working with Laravel, doing something like this is pretty easy.

So, if we want to display the string “item” in singular/plural based on the item count, here’s how we can do it using the plural helper method.

use Illuminate\Support\Str;

$itemCount = 1;
 
$cartItems = Str::of('item')->plural($itemCount);
// item

$itemCount = 5;

$cartItems = Str::of('item')->plural($itemCount);
// items

This can even process complex strings whose plural forms are somewhat unconventional.

$plural = Str::of('child')->plural(2);
 
// children
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!

Comments?