Using isset or array_key_exists to Verify Array Element Existence
When seeking to ascertain the presence of an array element, you can utilize either the isset language construct or the array_key_exists function.
isset
This approach is potentially more efficient because it is not a function. However, it may return false if the element exists but has a value of NULL.
Consider the following array:
<code class="php">$a = array( 123 => 'glop', 456 => null, );</code>
Using isset to test for element existence:
<code class="php">var_dump(isset($a[123])); // true var_dump(isset($a[456])); // false var_dump(isset($a[789])); // false</code>
array_key_exists
In contrast, array_key_exists evaluates solely the presence of the key, regardless of its value.
Using array_key_exists with the same array:
<code class="php">var_dump(array_key_exists(123, $a)); // true var_dump(array_key_exists(456, $a)); // true var_dump(array_key_exists(789, $a)); // false</code>
Choosing the Right Approach
For scenarios where the element is guaranteed to have a non-NULL value, isset may be preferable due to its efficiency. Otherwise, array_key_exists may be more suitable.
In your specific example, you can modify your code as follows using isset:
<code class="php">if (!isset(self::$instances[$instanceKey])) { $instances[$instanceKey] = $theInstance; }</code>
The above is the detailed content of Which PHP Construct Is Better for Verifying Array Element Existence: isset or array_key_exists?. For more information, please follow other related articles on the PHP Chinese website!