Skip to content

Instantly share code, notes, and snippets.

@petk
Last active October 13, 2024 00:23
Show Gist options
  • Save petk/4db6a5b0a2c5df7af0542cad86f7c372 to your computer and use it in GitHub Desktop.
Save petk/4db6a5b0a2c5df7af0542cad86f7c372 to your computer and use it in GitHub Desktop.
Testing for types, empty() and isset() in PHP

Testing for types, empty() and isset() in PHP

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)) {
    // ...
}

The empty() alternatives

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.

Testing for empty string

Replace:

if (empty($string)) {
    // ...
}

With:

if ($string === '') {
    // ...
}

Testing if a variable was declared in the scope

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.

Testing if a variable is null

Replace:

if (empty($variable)) {
    // ...
}

With:

if ($variable === null) {
    // ...
}

Testing that array has no elements

Replace:

if (empty($array)) {
    // ...
}

With:

if ($array === []) {
    // ...
}

Testing if array has a key

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])) {
    // ...
}

Testing objects and methods

// 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();

Testing if object has method

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();
}

Check if array item is array

function hook_preprocess($variables) {
    if (!is_array($variables['content']['#primary'] ?? null)) {
        return;
    }

    // ...
}

Assign empty array item with null coalesce operator

This array item gets assigned to an empty array, only when it is not set yet:

$array[$i] ??= [];

Read more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment