Bijan
Bijan

Reputation: 8594

Simple way to pick first variable that exists

Is there a simple way to input a couple variables and return the first one that exists?

For example, either $_POST['a'][$field] or $_POST['b'][$field] will exist – only one or the other, never both.

I want to assign whichever variable exists to a variable.

I was hoping for a syntax like this:

$field = $_POST['a'][$field] or $_POST['b'][$field];

but this will only return $_POST['a'][$field] (if it exists) or NULL

And I do know that I can do:

if(isset($_POST['a'][$field])){
    $field = $_POST['a'][$field];
} else {
    $field = $_POST['b'][$field];
}

but I was wondering if there is something more simple that I am not thinking of.

Upvotes: 1

Views: 109

Answers (1)

miken32
miken32

Reputation: 42698

You can use the null coalesce operator. It can be chained it as many times as you need, so you can also have a default value if neither is selected.

$field = $_POST['a'][$field] ?? $_POST['b'][$field] ?? "default";

Upvotes: 4

Related Questions