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;
    }
}
1
  • 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"; Commented May 18, 2022 at 13:34

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

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.
OK, I edited the answer, unfortunately I see no way to avoid the double $model->name in the expression.
this code will cause an error if $input->name is not set
It's throws a warning - you can prevent this by using isset($input->name).
Thank you for your answer. Although I find it not really easier/more readable than the nested ifs

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.