Question

I'm new to PHP. I just started working on it.

I'm trying to get the plural form using gettext and PHP. My code is as follows:

printf (ngettext ("%d product", "%d products", 2), 2);       

Output:

2 products

But, I want to have this o/p in a variable. When I try to give it as:

$totalItemsCount = printf (ngettext ("%d product", "%d products", 2), 2);
echo "Total count msgs::",$totalItemsCount;

Output:

10

Am I missing anything?

Was it helpful?

Solution

printf() displays a string, sprintf() returns it. However, printf() has a return value - it returns the string length. In this case, the resultant string is 2 products, and the length of this string is 10.

From the documentation for printf():

Return Values:

Returns the length of the outputted string.

If you want to store the output in a variable, use sprintf() instead.

$totalItemsCount = sprintf (ngettext ("%d product", "%d products", 2), 2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top