Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

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.

Upvotes: 2

Views: 2080

Answers (5)

SteeveDroz
SteeveDroz

Reputation: 6136

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...

Upvotes: 1

Paolo Stefan
Paolo Stefan

Reputation: 10253

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

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

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.

Upvotes: 2

BoltClock
BoltClock

Reputation: 723498

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

Upvotes: 7

93196.93
93196.93

Reputation: 2761

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

Upvotes: 0

Related Questions