DEV Community

Discussion on: Share your favourite PHP trick!

Collapse
 
bertheyman profile image
Bert Heyman • Edited

Personally, I'm a big fan of the ?? syntax (available from PHP 7 and up).

An example:

<?php

// Long syntax
!empty($book->author->name) ? $book->author->name : 'no known author'

// Short syntax with the coalescing operator
$book->author->name ?? 'no known author'

// Chaining ?? can tidy up your views (arbitrary example here)
Hello, <?= $user->nickname ?? $user->name ?? 'stranger' ?>
Enter fullscreen mode Exit fullscreen mode