title: PHP: Fastest way to handle undefined array key
body: <p>in a very tight loop I need to access tens of thousands of values in an array containing millions of elements. The key can be undefined: In that case it shall be legal to return NULL without any error message:</p>
  <p>Array key exists: return value of element.
  Array key does not exist: return null.</p>
  <p>I do know multiple solutions:</p>
  <pre><code>    if (isset($lookup_table[$key])) {
          return $lookup_table[$key];
      } else {
          return;
      }
  </code></pre>
  <p>or</p>
  <pre><code>@return $lookup_table[$key];
  </code></pre>
  <p>or</p>
  <pre><code>error_reporting(0);
  $return = $lookup_table[$key];
  error_reporting(E_ALL);
  return $return;
  </code></pre>
  <p>All solutions are far from optimal:</p>
  <ul>
  <li>The first one requires 2 lookup in the B-TREE: One to check existence, another to retrieve value. That effectively doubles the runtime.</li>
  <li>The second one uses the error suppression operator, and thus creates a massive overhead on that line.</li>
  <li>The third one calls the error handler (that will check error_reporting setting and then display nothing) and thereby creates an overhead.</li>
  </ul>
  <p><strong>My question</strong> is if I miss a way to avoid error handling and yet work with a single Btree lookup?</p>
  <h2>To answer some questions:</h2>
  <p>The array caches the results of a complex calculation - to complex to be done in real time.
  Out of billions of possible values, only millions yield a valid result. The array looks like 1234567 =&gt; 23457, 1234999 =&gt; 74361, .... That is saved to a PHP file of several megabyte, and include_once-d at the beginning of the execution. Initial load time does not matter.
  If the key is not found, it simply means that this specific value will not return a valid result. The trouble is to get this done 50k+ per second.</p>
  <h2>Conclusion</h2>
  <p>As there is no way found to get the value with a single lookup and without error handling, I have trouble accepting a single answer. Instead I upvoted all the great contributions.</p>
  <p>The most valuable inputs where:</p>
  <ul>
  <li>use array_key_exists, as it is faster than alternatives</li>
  <li>Check out PHP's QuickHash</li>
  </ul>
  <p>There was a lot of confusion on how PHP handles arrays. If you check the source code, you will see that all arrays are balanced trees. Building own lookup methods is common in C and C++, but is not performant in higher script-languages like PHP.</p>