将默认值分配给变量的最短方法? [英] Shortest way to assign a default value to a variable?

查看:65
本文介绍了将默认值分配给变量的最短方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有权使用cookie值(如果存在),否则使用默认值:

I have this right now to use a cookie value if exists otherwise use a default value:

$default_carat_min = "0.25";
if($_COOKIE["diamond-search_caratMin"])
{
    $default_carat_min = $_COOKIE["diamond-search_caratMin"];
}

我将不得不使用很多变量,会变得非常混乱/丑陋。因此,我尝试提出一种更简洁的书写方式。

I am going to have to do this with a lot of variables, and its going to get really cluttered/ugly. So I am trying to come up with a cleaner way of writing this.

我尝试过:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] | "0.25";

哪个没有用。

I可以这样做:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] ? $_COOKIE["diamond-search_caratMin"] : "0.25";

但是我不喜欢重复 $ _ COOKIE 两次。我想知道是否可以像第二个示例那样编写它?

But I don't like how I have to repeat the $_COOKIE twice. I am wondering if there is a way to write it something like my 2nd example?

推荐答案

PHP 5.3为< a href = http://www.php.net/manual/zh-CN/language.operators.comparison.php#language.operators.comparison.ternary rel = noreferrer>三元运算符:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] ?: "0.25";

如果左侧为true,则向左侧求值,否则为右侧。

Which evaluates to the left side if the left side is true, and evaluates to the right side otherwise.

在5.3之前,您必须使用长格式。

Prior to 5.3, however, you'd have to use the long form.

这篇关于将默认值分配给变量的最短方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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