Many times you might want to check if some variable has been set and it holds a non-falsy value.
With PHP loose typing:
if (isset($variable) && !empty($variable)) {
// ...
}
or this:
if (isset($variable) && $variable) {
// ...
}
is completely unnecessary. This can be simplified to a single empty()
test:
if (!empty($variable)) {
// ...
}
In the strict type era of PHP, you should also do your best to avoid empty()
altogether. Because in PHP, empty can mean a lot of things:
empty('');
empty(0);
empty(null);
empty(false);
empty(0.0);
empty('0');
empty([]);
The isset()
is more clear but it can still be avoided in most cases. It
applies only when the variable has not been declared in the scope or if its
value is null
.
To communicate the variable intent and its type more clearly, the following ways can be used.
Replace:
if (empty($string)) {
// ...
}
With:
if ($string === '') {
// ...
}
Replace:
if (!empty($variable)) {
// ...
}
With:
if (isset($variable)) {
// ...
}
However, if you need to check if the variable has been declared, there is most likely also something wrong in the code. Variables should always be declared in the scope so there are no unwanted surprises.
Replace:
if (empty($variable)) {
// ...
}
With:
if ($variable === null) {
// ...
}
Replace:
if (empty($array)) {
// ...
}
With:
if ($array === []) {
// ...
}
Replace:
if (!empty($array[$key])) {
// ...
}
With:
if (array_key_exists($key, $array)) {
// ...
}
// Or if you know that existance also means a non-empty value.
if (isset($array[$key])) {
// ...
}
// Let's suppose that find() method can return either object of class User or
// null if no user has been found in the database.
$user = $repository->find(1);
if ($user === null) {
return;
}
// Now you can call a method on the user object.
$email = $user->getEmail();
In PHP 8, this is can be simplified with the nullsafe operator:
$email = $repository->find(1)?->getEmail();
You can check if some object has some method in multiple ways:
if (is_callable($entity, 'id')) {
$id = $entity->id();
}
or:
if (method_exists([$entity, 'id'])) {
$id = $entity->id();
}
However, a simpler, recommended, and cleaner way is using interfaces:
if ($entity instanceof \Drupal\Core\Entity\EntityInterface) {
$id = $entity->id();
}
function hook_preprocess($variables) {
if (!is_array($variables['content']['#primary'] ?? null)) {
return;
}
// ...
}
This array item gets assigned to an empty array, only when it is not set yet:
$array[$i] ??= [];