简体   繁体   中英

PHP - checking key existence in an array

I have a file that contains a two denominational array:

<?php
return [
   'key1' => 'value1' ,
   'key2' => 'value2' ,
   'key3' => 'value3'
];
?>

I need to test for the presence of an array key. I am wondering what is the most efficient way of doing so? What is going to give me the fastest response time? At present this file is 1.2 megs. It is going to grow to the range of 10 megs.

Ron

I think usually built-in functions is more efficient and fast. So, try to use php array_key_exist function in this way:

if (array_key_exists("key",$array))
  return true;

Most efficient would be to use some better key-value store than array (SQLite, Redis, etc...). In all other ways you'll end up consuming memory, since array is initiated and memory is consumed in all cases.

If you don't mind consuming memory and are trying to be efficient on CPU side and each array member has value, then probably...

$array = include('myfile.php');
if (isset($array[$mykey])) {
  echo "is set\n";
}

... is most efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM