Plural and Singular terms in PHP

3k views Asked by At

I am doing an amount of users check for our website, below is the code. How can i use the word "user" if there is only 1 account and how can i use "users" if there is >1.

code:

       $result = mysql_query("SELECT * FROM users WHERE user_id='$userid'");
       $num_rows = mysql_num_rows($result);

        echo "amount of users.";
4

There are 4 answers

2
Adam Arold On BEST ANSWER

Maybe I get it wrong, but it is obvious:

echo $num_rows > 1 ? 'users' : 'user';
2
Nalum On

Try

if($num_rows === 1)
{
    echo "user";
}
else
{
    echo "users";
}

or in short form

echo $num_rows === 1 ? "user" : "users";
0
jondavidjohn On
if ($num_rows === 1) {
    echo "a user.";
}
else if ($num_rows > 1) {
    echo "amount of users.";
}
else {
    echo "no users".
}
0
Adam On

All of these answers will work well, but if you're looking for a reusable way, you can always externalise it:

function get_plural($value, $singular, $plural){
    if($value == 1){
        return $singular;
    } else {
        return $plural;
    }
}

$value = 0;
echo get_plural($value, 'user', 'users');

$value = 3;
echo get_plural($value, 'user', 'users');

$value = 1;
echo get_plural($value, 'user', 'users');

// And with other words
$value = 5;
echo get_plural($value, 'foot', 'feet');

$value = 1;
echo get_plural($value, 'car', 'cars');

Or, if you want it to be even more automated, you can set it up to only need the $plural variable set when it is an alternate word (eg: foot/feet):

function get_plural($value, $singular, $plural = NULL){
    if($value == 1){
        return $singular;
    } else {
        if(!isset($plural)){
            $plural = $singular.'s';
        }
        return $plural;
    }
}

echo get_plural(4, 'car');   // Outputs 'cars'
echo get_plural(4, 'foot');  // Outputs 'foots'
echo get_plural(4, 'foot', 'feet');  // Outputs 'feet'