三元运算符和if条件之间有区别吗? [英] Is there difference between ternary operator and if condition?

查看:124
本文介绍了三元运算符和if条件之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

三元运算符和php中的条件之间是否有区别?

Is there difference between ternary operator and if condition in php ?

如果是,请提供。

推荐答案

三元运算符是 operator ,因此它构成了一个表达式。因此它将具有一个值,您可以将其分配给变量,也可以根据需要使用。它用于简单的情况,其中变量可以根据条件接受两个可能的值。

The ternary operator is an operator, so it forms an expression. So it will have a value that you can assign to a variable or use however you want. It is used for simple situations where a variable can take two possible values depending on a condition.

例如: $ status = $ age> 18岁'adult':'child';

尽管可能,您不应嵌套三元运算符

控制结构 if 是完全不同的东西。他们唯一的共同点是两者都评估条件(对/错)。 if 用于根据该条件的结果执行代码片段。大多数情况下,您会发现自己使用 if (实际上,您可以不用三元生活)。在某些情况下,如果用三元数替换某些类型的 if ,则代码更少,可读性更高,例如:

The control structure if is something absolutely different. The only thing they have in common that both evaluate a condition (true/false). if is used to execute code fragments based on the result of that condition. You will find yourself using if most of the time (in fact, you can live without the ternary). In certain situations, it is less code and more readable if you replace certain types of ifs with the ternary, like this one:

if ($age > 18) {
    $status = 'adult';
} else {
    $status = 'child';
}

这篇关于三元运算符和if条件之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆