Clean Code
Comparison
Use identical comparison
Bad:
The loose comparison will convert the string into an integer.
$a = '42';
$b = 42;
if ($a != $b) {
// The expression will always pass
}
The comparison $a != $b returns FALSE but in fact it's TRUE! The string 42 is different from the integer 42.
Good:
The identical comparison will compare type and value.
$a = '42';
$b = 42;
if ($a !== $b) {
// The expression is verified
}
The comparison $a !== $b returns TRUE.
Null coalescing operator
Null coalescing is an operator introduced in PHP 7. The null coalescing operator ?? has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.
// BAD
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
// GOOD
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
