哪个更快:in_array或数据库查询?

Which is faster?

  1. I store the SQL results in an array - which means 1000 or more IDs. And then I use in_array() function 30 times to find out MyID is in the database.

  2. I check MyID is in the database and repeat it 30 times.

Test results:

48 records (MyID)

Array count: 1704 (ID) (Table size: 100 000)

Delta time:

Method 1: 0.0075759887695312

Method 2: 0.0038831233978271

I would definitely say that getting all ID's in array at one go will be much faster that querying MySQL server 30 times.

Neither of your proposed solutions seem right. You should look in to MySQL's IN clause. With this, you can WHERE for multiple values in a single query, like so:

SELECT something FROM table WHERE id IN(1, 4, 5, ...)

Use a (key,value) associative array instead (actually all arrays are associative in PHP but this is not the point). Set the keys of the array as ID, and each value is (for instance) 1.

$ids = array();
For all ID from database {
   $ids[ ID ] = 1;
}

To test if ID is in the array

if (isset($ids[ ID ])) {
   // yes it is 
}

using an array this way is very fast as internally the keys are stored as a tree - the search complexity is ~ O(1)