简体   繁体   中英

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 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"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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