Home > Backend Development > PHP Tutorial > Which PHP Construct Is Better for Verifying Array Element Existence: isset or array_key_exists?

Which PHP Construct Is Better for Verifying Array Element Existence: isset or array_key_exists?

Mary-Kate Olsen
Release: 2024-10-19 06:22:02
Original
554 people have browsed it

Which PHP Construct Is Better for Verifying Array Element Existence: isset or array_key_exists?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template