Taimur Aziz
Taimur Aziz

Reputation: 764

setting values if they don't already exist

What's the best way for setting values if they don't already exist in PHP?

Is it safe to use

$color = $option['color'] ?: 'blue';

Instead of

$color = isset($option['color']) ? $option['color'] : 'blue';

Or there's a much better way?

Upvotes: 3

Views: 69

Answers (2)

Oli Crt
Oli Crt

Reputation: 1173

In PHP 7 you can now use the Null coalescing operator:

$color = $option['color'] ?? 'blue';

This is the same as this in PHP5:

$color = isset($option['color']) ? $option['color'] : "blue";

Upvotes: 10

FranLMSP
FranLMSP

Reputation: 21

Both are the same, but $color = isset($option['color']) ? $option['color'] : 'blue'; prevents a PHP Warning exception

Upvotes: 1

Related Questions