1

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.

3
  • @Epodax the null coalesce operator was introduced to write less code for situations like this. Remark that $var appears 3 times in your example and only 2 times in the code posted in the question. Your suggestion pushes it in the wrong direction. Commented Mar 8, 2016 at 12:31
  • @axiac - You learn something new every day, however, why not provide this as a answer / soloution for OP? It seems like it's exactly what OP needs? Commented Mar 8, 2016 at 12:36
  • @Epodax the null coalesce operator is what the OP uses right now. She searches for a way to write even shorter code, to write the long expression from the left hand side of the assignment ($var in your example) only once. The operator she proposes does not (yet) exist in PHP. Commented Mar 8, 2016 at 12:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.