Plural and Singular terms in PHP
I am doing an amount of users check for our website, below is the code. How can i use the word "user" i开发者_运维知识库f 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.";
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'
Maybe I get it wrong, but it is obvious:
echo $num_rows > 1 ? 'users' : 'user';
if ($num_rows === 1) {
    echo "a user.";
}
else if ($num_rows > 1) {
    echo "amount of users.";
}
else {
    echo "no users".
}
Try
if($num_rows === 1)
{
    echo "user";
}
else
{
    echo "users";
}
or in short form
echo $num_rows === 1 ? "user" : "users";
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论