0

I just encounter a syntax expression while working with laravel model.

  public function address($type)
    {
        return $this->address[$type] ?? [];
    }

I don't understand how does this

 return $this->address[$type] ?? [];

Work?

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
Fil
  • 5,450
  • 10
  • 43
  • 67
  • 3
    Possible duplicate of [Reference — What does this symbol mean in PHP?](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Daniel Aug 03 '18 at 08:39

1 Answers1

4

It's the null coalescing operation (see more at https://en.wikipedia.org/wiki/Null_coalescing_operator#PHP). It's a syntactic shortcut for isset, really:

return $this->address[$type] ?? [];

can be read as:

if (isset($this->address[$type])) {
  return $this->address[$type];
} else {
  return [];
}
Adam Wright
  • 47,483
  • 11
  • 126
  • 149