美文网首页
isset和array_key_exits区别、性能

isset和array_key_exits区别、性能

作者: 老陈的记事本 | 来源:发表于2019-07-23 16:32 被阅读0次

一个基本的区别是isset()可用于数组和变量,而array_key_exits()只能用于数组。

但是最主要的区别在于在设定的条件下的返回值。

array_key_exists()

array_key_exists() 会检查键值的存在. 这个函数会返回TRUE,只要键值存在,即使值为NULL.

$arr = array( "one"=>"1", "two"=>"2", "three"=>null ); 
array_key_exists("one", $arr); // true 
array_key_exists("two", $arr); // true 
array_key_exists("three", $arr); // true

isset()

和arrry_key_exitst()不同,isset()会同时检查键和值,只有当健存在,对应的变量不为NUll的时候才会返回TURE。

$arr = array( "one"=>"1", "two"=>"2", "three"=>null );
isset($arr["one"]); // true 
isset($arr["two"]); // true 
isset($arr["three"]); // false

isset和array_key_exits执行效率

isset() > array_key_exists() > in_array()
数据量越大,性能差距越大

isset() 和 array_key_exists() 性能

也就是说,isset()+!is_null() 可以实现array_key_exists()的效果
isset() AND !is_null()

isset() 和 array_key_exists() 性能测试结果(1)

array_key_exists : 2.61410689354
is_set : 0.0547709465027
isset() + array_key_exists : 0.0560970306396
isset AND !is_null: 0.909719944

isset() 和 array_key_exists() 性能测试结果(2)

<?php 
$a = array('a'=>1,'b'=>2,'c'=>3,'d'=>4, 'e'=>null); 
$s = microtime(true); 
for($i=0; $i<=100000; $i++) { 
     $t= array_key_exists('a', $a); //true 
     $t= array_key_exists('f', $a); //false
     $t= array_key_exists('e', $a); //true 
} 

$e = microtime(true); 
echo 'array_key_exists : ', ($e-$s); 

$s = microtime(true); 
for($i=0; $i<=100000; $i++) { 
     $t = isset($a['a']); //true 
     $t = isset($a['f']); //false
     $t = isset($a['e']); //false 
} 

$e = microtime(true); 
echo 'is_set : ' , ($e-$s); 

$s = microtime(true); 
for($i=0; $i<=100000; $i++) { 
     $t= (isset($a['a']) || array_key_exists('a', $a)); //true 
     $t= (isset($a['f']) || array_key_exists('f', $a)); //false
     $t= (isset($a['e']) || array_key_exists('e', $a)); //true 
} 

$e = microtime(true); 
echo 'isset() + array_key_exists : ', ($e-$s); 
?> 

array_key_exists() : 308 ms
is_set() : 4.7ms
isset() + array_key_exists() :217ms

相关文章

网友评论

      本文标题:isset和array_key_exits区别、性能

      本文链接:https://www.haomeiwen.com/subject/tjdalctx.html