views:

52

answers:

1

Say I have a hashmap,

$hash = array('fox' => 'some value',
              'fort' => 'some value 2',
              'fork' => 'some value again);

I am trying to accomplish an autocomplete feature. When the user types 'fo', I would like to retrieve, via ajax, the 3 keys from $hash. When the user types 'for', I would like to only retrieve the keys fort and fork. Is this possible?

What I was thinking was using binary search to isolate the keys with 'f', instead of brute-force searching. Then continue eliminating the indexes as the user types out their query. Is there a more efficient solution to this?

Edit: Regarding wildcards, what I was wondering is that if there's a way to do $hash["f*"], returning all indexes that start with 'f'.

+5  A: 

This should do the trick:

$matches = preg_grep('/^for/', array_keys($hash));

and you'd end up with

$matches[0] = 'fort';
$matches[1] = 'fork'

from which you can refer back to the original $hash array.

Marc B
Curses! Your answer is better than the one I was writing! (+1)
Syntax Error
Just make sure you're using preg_quote!
MiffTheFox