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.
$test = array("hi" => "123");
isset($test["hi"]) ? unset($test["hi"]);
Why does this give a parse error? What is 开发者_Python百科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. Plus, your ternary operator is incomplete (missing a :
component).
How is an if statement that much longer anyway?
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($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. This construct is not a shorthand for if
statements and you are attempting to use it not for what it was designed.
Use an if
statement:
if (isset($test['hi']))
unset($test['hi']);
There's also the slightly more explicit array_key_exists
. Compare its documentation with that of isset
to determine which is the more appropriate for your needs.
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 = array("hi" => "123");
!isset($test["hi"]) ?: unset($test["hi"]);
精彩评论