Php: Fastest Way to Handle Undefined Array Key

PHP: Fastest way to handle undefined array key


Since PHP 7 you can accomplish this with the null coalesce operator:

return $table[$key] ?? null;

Old answer

First of all, arrays are not implemented as a B-tree, it's a hash table; an array of buckets (indexed via a hash function), each with a linked list of actual values (in case of hash collisions). This means that lookup times depend on how well the hash function has "spread" the values across the buckets, i.e. the number of hash collisions is an important factor.

Technically, this statement is the most correct:

return array_key_exists($key, $table) ? $table[$key] : null;

This introduces a function call and is therefore much slower than the optimized isset(). How much? ~2e3 times slower.

Next up is using a reference to avoid the second lookup:

$tmp = &$lookup_table[$key];

return isset($tmp) ? $tmp : null;

Unfortunately, this modifies the original $lookup_table array if the item does not exist, because references are always made valid by PHP.

That leaves the following method, which is much like your own:

return isset($lookup_table[$key]) ? $lookup_table[$key] : null;

Besides not having the side effect of references, it's also faster in runtime, even when performing the lookup twice.

You could look into dividing your arrays into smaller pieces as one way to mitigate long lookup times.

Beginner php Warning: Undefined array key

I'll assume you want to know how to get rid of this error message.

The first time you load this page you display a form and $_GET is empty (that's why it is triggering warnings). Then you submit the form and the fname and age parameters will be added to the url (because your form's method is 'get').

To resolve your issue you could wrap the two lines inside some if-statement, for example:

<?php if(isset($_GET['fname']) && isset($_GET['age'])): ?>
Your name is <?php echo $_GET["fname"]; ?>
Your age is <?php echo $_GET["age"]; ?>
<?php endif; ?>

Why it shows Undefined array key title error?

I see you just missed one level in comment object:

'name' => "post_comments",
'data' => [
'comments' =>
collect($post['comments'])->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],

Is there an idiomatic way to get a potentially undefined key from an array in PHP?

More elegant way of doing it:

function ifsetor(&$value, $default = null) {
return isset($value) ? $value : $default;

Now you can just do:

$value   = ifsetor($arr[$key]);
$message = ifsetor($_POST['message'], 'No message posted');

etc. Here $value is passed by reference, so it wouldn't throw a Notice.

Further reading:

  • NikiC's blog — The case against the ifsetor function
  • PHP RFC —

Related Topics

Leave a reply