PHP:如果Else条件赋值给变量并调用string

时间:2012-08-16 19:18:18

标签: php variables conditional

这可能是一个简单而愚蠢的问题,但首先我正在学习php,所以你的帮助将不胜感激。

我正在尝试使用指定的条件语句获取变量。

$gender = $curauth->gender; // getting from wordpress user profile.

if($gender === 'Male') {
    echo 'his';
} else {
    echo 'her';
}

所以我想要做的是它会检查用户是否是男性,而不是在某些描述中它将使用他的,如果是女性,它将使用她。像下面的东西

echo 'jatin soni doesn't have set this option yet. His option will be deactivated soon.';

所以这里他的将使用上面的条件代码设置。

4 个答案:

答案 0 :(得分:5)

你可以直接echo

echo 'jatin soni doesn\'t have set this option yet. ', 
     ($gender === 'Male' ? 'His' : 'Her'), 
     ' option will be deactivated soon.';

如果您需要多次或出于可读性原因,则应将其分配给变量:

# Default Female:
$gender = empty($curauth->gender) ? 'Female' : $curauth->gender;

$hisHer = $gender === 'Male' ? 'His' : 'Her';
echo 'jatin soni doesn\'t have set this option yet. ', 
     $hisHer, 
     ' option will be deactivated soon.';

下一步可以是double-quoted stringsDocs中的变量替换或使用printfDocs函数进行格式化输出。

答案 1 :(得分:4)

这个怎么样?

<?php
$pronoun = $curauth->gender == 'Male' ? 'his' : 'her';
echo "Jatin Soni doesn't have set this option yet. " .
     ucfirst($pronoun) . " option will be deactivated.\n"
?>

答案 2 :(得分:3)

最常见的做法是将动态部分分配给变量,然后在输出中使用变量:

$gender = $curauth->gender; // getting from wordpress user profile.

if ($gender === 'Male') {
    $hisHer = 'His';
} else {
    $hisHer = 'Her';
}

echo "jatin soni doesn't have set this option yet. $hisHer option will be deactivated soon.";

答案 3 :(得分:1)

如果您想要变量,可以在一行中完成:

$gender = $curauth->gender; // getting from wordpress user profile.
$their = $gender == 'Male' ? $gender = 'His' : $gender = 'Her';
echo "$username doesn't have set this option yet. $their option will be deactivated soon.";