Midori Kocak
Midori Kocak

Reputation: 121

Repeated Variable at PHP 7 Null Coalescing operator

Look at this code:

$this->request->data['comments']['user_id'] = 
    $this->request->data['comments']['user_id'] ?? ‘value’;

I want to check if some var is null and if the same var is null set the same var to ‘value’.

Hence I am repeating the same variable after the equal operator, this does not feels right.

So I feel that we need another operator like ??= similar to +=:

$this->request->data['comments']['user_id’] ??= ‘value’.

So if the var is null it’s set to ‘value’ and else stays the same.

Upvotes: 1

Views: 84

Answers (2)

Midori Kocak
Midori Kocak

Reputation: 121

I implemented this operator and made a pull request for PHP7. Currently it's on RFC stage and if it's accepted, it is going to be merged to PHP version 7.x.

https://wiki.php.net/rfc/null_coalesce_equal_operator

Upvotes: 2

Alex Shesterov
Alex Shesterov

Reputation: 27525

Just create a utility function for this purpose:

function assignIfNotSet(&$variable, $value) {
    if (!isset($variable)) {
        $variable = $value;
    }
}

It will assign a value to the $variable if and only if its value is null or not set.

The function makes use of passing variables by references — see docs.

Usage:

$x = "original value";
assignIfNotSet($x, "other value");
var_dump($x); // "original value"

$y = null;
assignIfNotSet($y, "other value");
var_dump($y); // "other value"

// assuming $z wasn't previously defined
assignIfNotSet($z, "other value");
var_dump($z); // "other value"

It also works for array items and object properties. In your case:

assignIfNotSet($this->request->data['comments']['user_id'], 'value');

Upvotes: 0

Related Questions