Comparison of PHP isset and array_key_exists

 essence. PHP isset is a language structure, and array_key_exists is a function, which executes There is a difference in speed, and more importantly, in some cases, the results returned by the two are different. Many engineers hope to increase the performance of program execution and use isset to process array key queries. But not all situations are suitable to use isset to replace array_key_exists .


Basic syntax of PHP isset and array_key_exists

bool isset (array key to be checked); bool array_key_exists (key name $key to be queried, PHP array to be checked)


It can be known from the syntax that both of them are returning the Boolean value, that is, TRUE OR FALSE. The two seemingly similar usages are actually different.

PHP isset and array_key_exists return the difference
<?php
$NewArray = array('A' => null,'B' =>'');
if (isset($NewArray[A])) {
 echo "Use isset to find the key name A in the array<br> ";
}
if (isset($NewArray[B])) {
 echo "Use isset to find the key name B in the array<br>";
}
if (array_key_exists('A', $NewArray)) {
 echo "Use array_key_exists to find The array contains the key name A<br>";
}
if (array_key_exists('B', $NewArray)) {
 echo "Use array_key_exists to find the key name B in the array";
}
?>
The above output
Use isset to find the key name B
in the array Use array_key_exists to find the key name A
in the array Use array_key_exists to find the key name B in the array
From the output result of the example, we can see that PHP isset will return false when the array key value is null. Therefore, after the first pass of the if condition is judged, there will be no result output, but the second time the key name B is found. I found it because although $NewArray[B] is a null value, it is not null, which is also different. Let’s take a look at the array_key_exists function. No matter whether the key name of the query has a value or null, as long as it is found, it will return true. This is one of the main differences between the two. After this point is clear, we will design PHP in the future How to choose these two methods can be mastered correctly.

Post a Comment

0 Comments