PHP

Faster Array Search in PHP

I used to use in_array() function to find if a string exist in an array. But then I find out that there’s a faster method to do this using isset().

First method, using in_array() function:

< ?php $nama = array("yuna","sakura","miyabi","sena"); if(in_array("yuna",$name)) echo "we have yuna here!"; ?>

and seem it’s too slow. PHP will loop the array and check one by one to see if we have yuna in the array.

Then using isset() function as follow:

< ?php $nama = array("yuna","sakura","miyabi","sena"); if(isset($name['yuna'])) echo "we have yuna here!"; ?>

it will just check if yuna is exist, no loop, no pain.

3 Comments

  1. I think you will find that this won’t actually work as:
    [php]isset($nama[‘yuna’])[/php]
    is checking to see if the key ‘yuna’ exists in the $nama array. In reality you have created an indexed based array so this function will always return false.
    If you were to try this instead you will get the result you are looking for:
    [php]isset($nama[0])[/php]
    Of course this still does not answer your speed issue with searching the array. Maybe you could write your sort and search algorithm for associateive arrays.

  2. huuh jeng . .
    tuh buat nggantiin array_key_exists()
    bukan in_array()

  3. Second the PHP manual:

    “isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does. ”

    The PHP manual example:

    $search_array = array(‘first’ => null, ‘second’ => 4);

    // returns false
    isset($search_array[‘first’]);

    // returns true
    array_key_exists(‘first’, $search_array);

    Regards

Leave a Reply