phparraysarray-key-exists

array_key_exists($key, $array) vs !empty($array[$key])


I've seen a lot of people do the former, is there any performance benefit doing one vs the other? Or is it just an eye candy? I personally use the latter every time as it is shorter and personally more readable to me.


Solution

  • The other responses focus on the differences between the two functions. This is true, but if the source array does not contain null or 0 or "", ... (empty values) values you can benchmark the speed of the two functions:

    <?php
    
    function makeRandomArray( $length ) {
        $array = array();
        for ($i = 0; $i < $length; $i++) {
            $array[$i] = rand(1, $length);
        }
    
        return $array;
    }
    
    function benchmark( $count, $function ) {
        $start = microtime(true);
        for ($i = 0; $i < $count; $i++) {
            $function();
        }
        return microtime(true) - $start;
    }
    
    $runs = 100000;
    $smallLength = 10;
    $small = makeRandomArray($smallLength);
    
    var_dump(benchmark($runs, function() {
        global $small, $smallLength;
        array_key_exists(rand(0, $smallLength), $small);
    }));
    var_dump(benchmark($runs, function() {
        global $small, $smallLength;
        !empty($small[rand(0, $smallLength)]);
    }));
    

    Which gave me the following results:

    For a small array:

    For a relative big array:

    So if it's possible it's faster to use empty or isset.

    Although, I would like to highlight that this is a micro-optimization and that most probably won't matter that much. You need to actually do proper profiling, to find where is the bottleneck in your application before you end up focusing on these small optimizations.