hitautodestruct
hitautodestruct

Reputation: 20832

What is the shortest way to check if a variable exists and return an alternative in php?

When I check for a return value of a function I usually do this:

$my_value = get_field('some_field');
$my_value = $my_value ? $my_value : get_field('backup');

In Javascript I usually use or (||) to check a value and if not return an alternative i.e.

var my_value = get_field('some_field') || get_field('backup');

Is there something equivalent in php?

Upvotes: 0

Views: 76

Answers (2)

Salketer
Salketer

Reputation: 15711

Even faster:

$my_value = get_field('some_field') ?: get_field('backup');

Note that it tests if get_field('some_field') is true or false, and if true, return its value, else get_field('backup')...

Upvotes: 1

Guns
Guns

Reputation: 2728

well you have got it almost:

here is what helps you:

$my_value = isset($my_value) ? $my_value : get_field('backup');

Upvotes: 1

Related Questions