PHP If shorthand

Asked by At

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.

5 Answers

Paolo Stefan On Best Solutions

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:

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

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"]);
Lightness Races in Orbit On

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']))

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.

SteeveDroz On

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

Even if $test["hi"] isn't set, you can still unset it...