Multiple and singular terms in PHP

I am doing the number of users checking our site, below is the code. How can I use the word "user" if there is only one account, and how can I use "users" if there is "1".

the code:

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

        echo "amount of users.";
+3
source share
4 answers

Maybe I'm wrong, but this is obvious:

echo $num_rows > 1 ? 'users' : 'user';
+5
source

All of these answers will work well, but if you are looking for a reusable path, you can always break 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 only set it for a variable $pluralif it is an alternative word (e.g. 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'
+8
source
if ($num_rows === 1) {
    echo "a user.";
}
else if ($num_rows > 1) {
    echo "amount of users.";
}
else {
    echo "no users".
}
+4
source

Try

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

or in short form

echo $num_rows === 1 ? "user" : "users";
+3
source

Source: https://habr.com/ru/post/1793609/


All Articles