php 变量中的 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9287398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If-statement in a Variable
提问by Visualizer7
I want to print the same page's name differently based on a certain variable.
我想根据某个变量以不同的方式打印相同页面的名称。
Here is a corresponding code.
这是相应的代码。
$metaTitle ="'if($variable=='input'){ title#1 }else { title#2 };'";
And the produced meta title is lately used in the same file to create the page title (<title></title>
)
并且最近在同一个文件中使用生成的元标题来创建页面标题 ( <title></title>
)
But it keeps producing the title like
但它不断产生这样的标题
if($variable=='input'){ title#1 }else { title#2 };
(the whole if statement as a whole. It does not recognize the if statement. It considers the statement as a plain text.)
(整个 if 语句作为一个整体。它不识别 if 语句。它将语句视为纯文本。)
What did I do wrong in the sentence??
我在句子中做错了什么??
回答by dpp
Use ternary operator "?:":
使用三元运算符“?:”:
$metaTitle = ($variable=='input')? "title#1" : "title#2";
The first part is the condition:
第一部分是条件:
($variable=='input')
The second is the result when condition is true:
第二个是条件为真时的结果:
"title#1"
The third is the result when condition is false:
第三个是条件为假时的结果:
"title#2"
Source http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
来源http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
回答by horsley
Because you just assign $metaTitle a STRING "'if($variable=='input'){ title#1 }else { title#2 };'" and it's not a runable statement
因为您只是为 $metaTitle 分配了一个 STRING "'if($variable=='input'){ title#1 }else { title#2 };'" 并且它不是一个可运行的语句
you should do like this
你应该这样做
if ($variable=='input') {
$metaTitle = "title#1";
} else {
$metaTitle = "title#2";
}
or simply use Ternary Operator
或简单地使用三元运算符
回答by davoclavo
The simplest and most basic solution is to set the title variable inside the if statement.
最简单和最基本的解决方案是在 if 语句中设置 title 变量。
if($variable=='input'){
$metaTitle = 'title#1';
} else {
$metaTitle = 'title#2';
}
回答by mbh
Try this instead -
试试这个 -
if($variable=='input')
{
$metaTitle = 'title#1';
}
else
{
$metaTitle = 'title#2';
}