简体   繁体   English

PHP如果速记

[英]PHP If shorthand

I would like to a simple if shorthand that check if an array has a particular key and if so unset it. 我想用一个简单的if速记来检查一个数组是否有一个特定的键,如果是这样的话,那么就不用了。

$test = array("hi" => "123");
isset($test["hi"]) ? unset($test["hi"]);

Why does this give a parse error? 为什么这会给出解析错误? What is the correct syntax. 什么是正确的语法。

You can't use unset() in a ternary conditional operator as that language construct doesn't return a value, and the operator expects to evaluate to some value, not execute a code block. 您不能在三元条件运算符中使用unset() ,因为该语言构造不返回值,并且运算符期望求值为某个值,而不是执行代码块。 Plus, your ternary operator is incomplete (missing a : component). 另外,您的三元运算符不完整(缺少a :组件)。

How is an if statement that much longer anyway? if语句如何更长?

if (isset($test["hi"])) unset($test["hi"]);

Because it is a ternary operator . 因为它是三元运算符 This code: 这段代码:

$a = ($condition)? $b : $c;

is equivalent to: 相当于:

if($condition) $a = $b;
else $a = $c;

For what you ask, there is no need for a check, you can simply unset() the array element without first checking it, and it would give no error messages: 根据你的要求,不需要检查,你可以简单地unset()数组元素而不先检查它,它不会给出任何错误消息:

unset($test["hi"]);

The ternary conditional operator looks like this: 三元条件运算符如下所示:

a ? b : c

You're missing that c clause, and your b clause is not an expression returning a value. 您缺少该c子句,并且您的b子句不是返回值的表达式。 This construct is not a shorthand for if statements and you are attempting to use it not for what it was designed. 这个结构不是 if语句的简写,而是你试图使用它而不是它的设计。

Use an if statement: 使用if语句:

if (isset($test['hi']))
    unset($test['hi']);

There's also the slightly more explicit array_key_exists . 还有更明确​​的array_key_exists Compare its documentation with that of isset to determine which is the more appropriate for your needs. 将其文档与isset文档进行比较,以确定哪个更适合您的需求。

You don't need to test anything. 你不需要测试任何东西。 If you try to unset a non-set variable, nothing happens. 如果您尝试取消设置非设置变量,则不会发生任何事情。

The equivalent to your code would be: 相当于您的代码将是:

$test = array("hi" => "123");
unset($test["hi"]);

Even if $test["hi"] isn't set, you can still unset it... 即使没有设置$test["hi"] ,你仍然可以取消它...

$test = array("hi" => "123");
!isset($test["hi"]) ?: unset($test["hi"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM