isset() or !empty() versus in_array()

I saw an interesting comment on stackoverflow about using a function to check if a variable exists such as isset() or empty() instead of using a search function such as in_array(). I hadn’t really given much thought to that before but it seems that it would be much quicker than looping an array to check for a value. I guess the caveat is that you would either need to know the index number or know the key name (if an associative array) to be able to make use of it.

For example:

$lunch = array('fruit' => 'Apple', 'snack' => 'Pudding', 'mainCourse' => 'Sandwich');

if (!empty($lunch['fruit'] and $lunch['fruit'] == 'Apple') {
// do something
}

The alternative I might have used would be

if (array_key_exists('fruit', $lunch) and $lunch['fruit'] == 'Apple') {
// do something
}

Ilia Alshanetsk wrote a blog post in which he compares the speed of using isset() versus array_key_exists with PHP 5.4. While isset() is quicker, it isn’t something that makes much sense to go back and fix (it falls into the micro-optimization category).

I decided to give his test a try and also check out how !empty() performs. I expected it would be somewhere between the two since empty() does an isset() check. I saw slightly different results checking on PHP 5.4.4, but those could be chalked up to not using the same server configuration (and in any case they are negligible).

isset() – 0.021 seconds
array_key_exists() – 0.068 seconds
!empty() – 0.025 seconds

Here is the code I used to generate my results:

$arr = array();
$fp = fopen("/usr/share/dict/words", "r");
while ($i < 5000 && ($w = fgets($fp))) {
    $arr[trim($w)] = ++$i;
}

$s = microtime(1);
for ($i = 0; $i < 100000; $i++) {
    isset($arr['abracadabra']);
}
$e = microtime(1);

echo "Isset: ".($e - $s)."\n";
echo '<br />';

$s = microtime(1);
for ($i = 0; $i < 100000; $i++) {
    array_key_exists('abracadabra', $arr);
}
$e = microtime(1);

echo "array_key_exists: ".($e - $s)."\n";
echo '<br />';

$s = microtime(1);
for ($i = 0; $i < 100000; $i++) {
    !empty($arr['abracadabra']);
}
$e = microtime(1);
echo "!empty(): ".($e - $s)."\n";

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>