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

3
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:

unset($test["hi"]);
0
93196.93 On
$test = array("hi" => "123");
!isset($test["hi"]) ?: unset($test["hi"]);
7
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"]);
2
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']))
    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.

1
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");
unset($test["hi"]);

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