Ron Piggott
Ron Piggott

Reputation: 705

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

Upvotes: 0

Views: 70

Answers (2)

hamed
hamed

Reputation: 8033

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;

Upvotes: 3

Kalle Volkov
Kalle Volkov

Reputation: 458

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.

Upvotes: 2

Related Questions