DEV Community

JohnDivam
JohnDivam

Posted on

Clean PHP: isset() and Null-Safe Operators

Refactor the isset condition in PHP, you can use the null coalescing operator in conjunction with the null-safe (also known as null propagation) operator to achieve the same result in a more concise way.

BAD

{{ (isset($rowData[$i]) ? $rowData[$i] : null) }}
Enter fullscreen mode Exit fullscreen mode

GOOD

{{ $rowData[$i] ?? null }}
Enter fullscreen mode Exit fullscreen mode

_Other Example _
BAD

if(isset($rowData['name'])){
 $name = $rowData['name'];
}
elseif(isset($rowData['fullname'])){
 $name = $rowData['fullname'];
}
else{
 $name = 'nobody';
}
Enter fullscreen mode Exit fullscreen mode

GOOD

$name = $rowData['name']) ?? $rowData['fullname']) ?? 'nobody'
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
n3rdnerd profile image
N3rdNERD

Great!