0

I only see use cases were null coalesing can be used to chain values, but not to omit any value.

Am I missing something essential or is there really no shorthand way to write this:

$model->name = "Example";

if(isset($input->name)) {
    $validName = $this->doSomeValidationEventualyReturnNull($input->name);
    if($validName) {
        $model->name = $validName;
    }
}
Alex
  • 29
  • 5
  • I am having a hard time reading the question title but your code could be shortened to $model->name = $this->doSomeValidationEventualyReturnNull($input->name ?? null) ?? "Example"; – Your Common Sense May 18 '22 at 13:34

1 Answers1

2

I can propose this one liner, has something to do with null coalescing.

$model->name = isset($input->name) ? ($this->doSomeValidationEventualyReturnNull($input->name) ?? $model->name) : $model->name;
Onki Hara
  • 270
  • 1
  • 9
  • Sorry, maybe I was not precise enough: the first line is just to complete the example. I only need a replacement for the nested if-clauses and leave the model untouched if there is no or invalid input. – Alex May 18 '22 at 13:25
  • OK, I edited the answer, unfortunately I see no way to avoid the double $model->name in the expression. – Onki Hara May 18 '22 at 13:28
  • 1
    this code will cause an error if $input->name is not set – Your Common Sense May 18 '22 at 13:29
  • It's throws a warning - you can prevent this by using `isset($input->name)`. – Onki Hara May 18 '22 at 13:42
  • 1
    Thank you for your answer. Although I find it not really easier/more readable than the nested ifs – Alex May 18 '22 at 14:42