php if{} ELSE IF{} else{} 简写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24286340/
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
shorthand php if{} ELSE IF{} else{}
提问by Timotheus Triebl
is there a possibility to write a shorthand if, ELSE IF, else statement for php.
是否有可能为php编写速记if,ELSE IF,else语句。
if / else is clear but is there a shorthanded way when i want to use elseif too (except switch)?
if / else 很清楚,但是当我也想使用 elseif 时(除了 switch)有没有捷径可走的方法?
if ($typeArray == 'date'){
echo 'date';
} else if($typeArray == 'time'){
echo 'time';
} else {
echo 'text';
}
Haven't found any good answer else, where there is a shorthand version for nested if statements including an elseif.
还没有找到任何好的答案,其中有嵌套 if 语句的速记版本,包括 elseif。
greetings timmi
问候蒂米
回答by Ing. Michal Hudak
You're looking for ternary statements.
您正在寻找三元语句。
Syntax:
句法:
$condition ? $value_if_true : $value_if_false
Syntax for nested ternary statements:
嵌套三元语句的语法:
$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )
Just a warning, nested ternary statements are hard to read, so it's recommended to unnested ternary statements.
只是一个警告,嵌套的三元语句很难阅读,因此建议使用非嵌套的三元语句。
回答by fdehanne
You can see this Ternary operator. Good when you have an if/else, but bad readability if you do more.
你可以看到这个三元运算符。当你有一个 if/else 时很好,但如果你做得更多,那么可读性就会变差。
Alternative syntax. This syntax is useful when you use html/php in the same code. It helps us to see the end of if/foreach/while...
替代语法。当您在同一代码中使用 html/php 时,此语法很有用。它帮助我们看到 if/foreach/while 的结束...
switch/case. The best is probably to post some code to see if it could be shortened.
开关/案例。最好的可能是发布一些代码,看看它是否可以缩短。