tags:

views:

51

answers:

2

I have a list of values I have to check my input against it for existence.
What is the faster way?

This is really out of curiosity on how the internals work, not any stuff about premature optimization etc...

1.

$x=array('v'=>'','c'=>'','w'=>);
..
..
array_key_exists($input,$x);

2.

$x=array('v','c','w');
..
..
in_array($input,$x);
A: 

in my experience, array_key_exists is faster 99% of the time, especially as the array size grows.

that being said, isset is even faster, as it does a hash lookup vs an array value search, though isset will return false on blank values, as shown in your example array.

Jason
`isset` works fine with "blank" values, though `NULL` would be the case to keep in mind.
salathe
empty will, not isset will not
Col. Shrapnel
damn, nice catch, wasn't thinking when i posted this :)
Jason
+2  A: 

How about isset($x[$input]) which, if suitable for your needs, would generally beat both of those presented.

Of the two methods in the question, array_key_exists has less work to do than in_array so if you had to choose between only those two then array_key_exists would be it.

Aside: Do you have any specific questions about "the internals"?

salathe
isset is even faster?
Itay Moav
@Itay isset is *shorter*
Col. Shrapnel
@Itay Moav, try it and see. In most cases it would be. And it's *shorter* thus saving our poor, tired fingers.
salathe
Yeah @Itay try it and see. But try using apache bemchmark with real code, not "zillion iterations of nothing"
Col. Shrapnel