Search in Key/ Index of an Associative PHP Array

I have to search in keys of associative PHP Array and not in value of an array. I want it to be fast as I need to search in long list and find something.
PHP function array_search() search in array's value part.
I got three methods which have provided working solutions with varying process time.
1. Using array_keys()
<?php
if (in_array ($search_term, array_keys($array1)))) {
    // Search item found
}
?>

Time taken = 4.02911
2. Using array_key_exists

<?php
if (array_key_exists ($search_term, $array1)) {
    // $search term found
}
?>

Time taken = 3.8229

3. Directly putting search term in key

<?php
if (isset ($array1[$search_term])) {
    // $search item found
}
?>

Time taken = 3.77827

Note: Time taken in not of this small code but by my program. But this still gives information. Search was used repeatedly in my program.

First two will always work. Third will fails when value part of a key will have NULL value. Those entry with NULL in value part will not be considered in the search method using isset() function.

Getting value of the matched key:
Now, you know that your key exist in an Array. How to get the searched key's value?
Suppose, $companyId is the key you searched above.
1. Generic method and not so tasty:


<?php
foreach ($shortCodes as $shortCode=>$CID)
{
   if ($CID == $companyId)
   {
	   $myShortCode = $shortCode;
	   break;
   }
}
?>

2. Useful and short one:


<?php
           $myShortCodeArr = array_keys($shortCodes, $companyId);
?>

It will return you array.

The above methods of searching works only for one Dimensional array. Once I run into problem of multidimensional array.
Here is a tested code working in Class.


class test {
    function test() {
        $orderRow = array('pick_up'=> 'US', 'test' => 2);
        array_walk_recursive($orderRow, array($this, 'myKey'));
        var_dump( $this->pickUp);
    }
    function myKey($item, $key) {
         if ($key === 'pick_up') {
            $this->pickUp = $item; // searched Term
        }
    }
}
$a = new test();

Passing "$this" is important for array_walk_recursive() working in class. Remove the $this var and it is ready for functional method.

  • # 1 - by NintendoAndMac

    The fastest way to search for a key in an array is ofcourse to do like this:
    $array['searchterm'].

Comment pages
1 2 267
Comments are open for an year period. Please, write here on Facebook page.