PHP 如果变量 = 1 新变量 = 别的东西
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7777705/
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
PHP if variable = 1 new variable = something else
提问by user976326
I want to do a test in PHP to see if form_id = "1"
then form_name = "Test form 1"
and then if the form_id = "2"
the form_name
would be "General Enquiries"
for example.
我想要做的PHP中的测试,看看是否form_id = "1"
再form_name = "Test form 1"
然后,如果form_id = "2"
该form_name
会"General Enquiries"
的例子。
How can this be one in PHP.
这怎么可能是 PHP 中的一个。
I can see how to echo a result but not turn it into a new variable.
我可以看到如何回显结果但不能将其转换为新变量。
Thanks Roy
谢谢罗伊
回答by bigblind
A simple if statement could do it:
一个简单的 if 语句就可以做到:
if($form_id==1)
$form_name='form 1 result';
elseif($form_id==2)
$form_name='general inquiries';
But this makes for many nested statements when you get more possible form id's, a switch statement solves this problem
但是当您获得更多可能的表单 ID 时,这会产生许多嵌套语句,switch 语句解决了这个问题
switch($form_id){
case 1:
$form_name='form 1 name';
break;
case 2:
$form_name='general enquiry';
break;
case 3:
$form_name='an added form';
break;
default:
$form_name='unknown form'
}
To learn more about the switch statement, go here
要了解有关 switch 语句的更多信息,请转到此处
There is also a short notation for conditional values, see it as an if statement with a variable assignment in short form.
条件值也有一个简短的表示法,将其视为带有简短形式的变量赋值的 if 语句。
$form_name = ($form_id == 1) ? 'form 1 result' : 'enquiery';
In this case, PHP first evaluates the expression before the question mark. If it is true, the value right behind the question mark is returned, otherwise, the value after the colon is returned. You can also nest these:
在这种情况下,PHP 首先计算问号之前的表达式。如果为真,则返回问号后面的值,否则返回冒号后的值。您还可以嵌套这些:
$form_name = ($form_id==1) ? ''form 1 result' : ($form_id==2) ? 'enquiry form' : 'unknown form';
EDIT from a slightly older, slightly more experienced me: I usually avoid nesting these expressions. It's often harder to understand than just using if-statements, or putting the "inner" ternary expression into its own variable.
来自一个稍微年长一些、稍微有经验的我的编辑:我通常避免嵌套这些表达式。通常比仅使用 if 语句或将“内部”三元表达式放入其自己的变量中更难理解。
回答by CodeCaster
You mean like this?
你的意思是这样?
if ($form_id == 1)
{
$form_name = "Test form 1";
}
elseif ($form_id == 2)
{
$form_name = "General Enquiries";
}
else
{
// do something
}
回答by Mob
if ($form_id == 1){ $formname = "Test form 1";}
if ($form_id == 2){ $formname = "General Enquiries";}
echo $formname;