PHP — Defensively checking array values

When writing code, it’s always a good practice to be as defensive as possible. Defensive coding is the practice of ensuring that your code functions appropriately for all possible error scenarios. One common error I see with PHP that can easily be defended is reading an undefined key from an array. I see this error from folks just starting out with PHP, to veterans who just missed it because it’s easy to forget.

In PHP, if you access a key that is not set, you will trigger a notice. For 
example, if we create a form with an input named e-mail, we could have some code like this:

$email = $_POST[‘email’]

This may seem innocuous, but if the key ‘email’ is missing, you will trigger an E_NOTICE like this:

PHP Notice: Undefined index: email

You cannot reliably access a key unless you first know that it is there. You have to work around it by using the isset function which suppresses notices when accessing unset variables*. By leveraging that function, we commonly see code like this:

$email = isset($_POST[‘email’]) ? $_POST[‘email’] : null;

In the case where the e-mail key is missing from the array, we read the key inside of the isset function, so the notice is suppressed. Isset returns false, so we skip to the false clause of the operator, which sets the value of $email to null.

This is a bit verbose, and you have to do this check a lot in a given codebase. Luckily, a feature was added in PHP7 to make this more simple: the null coalesce operator.

The null coalesce operator (??) works exactly like the isset check above, but with more straight-forward code, like this:

$email = $_POST[‘email’] ?? null;

The left operand of the null coalesce operator will check if the value is not null. If so, it will return the value. Otherwise, it will return the right operand. The left hand check of the null coalesce statement also suppresses errors, just like the isset function.

This is an cleaner way to prevent an unintended E_NOTICE while processing user input. It’s one of the smaller features of PHP7, but it’s a nice addition to have!


*Technically, isset is a language level construct and not a function. In the PHP engine, the notice isn’t suppressed; the error is never generated.

Like what you read? Give Daniel G. Sims a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.