James
James

Reputation: 43657

in_array problem

I have a couple of big arrays with numbers as items, each one has 5 000 - 10 000 values.

All are the simple arrays, like

$array = array(125,345345,345,3485,324,65,746647,3221, ... );

I'm trying to search them for some number, and repeat this operation nearly 1 000 times for different numbers.

Like

if $array has item 345 {
    return true
} else {
    return false
}

But the request takes a long time to finish. Sometimes server gives a timeout error.

What is the best way to search for some number in simple by structure, but big by their size arrays?

Upvotes: 3

Views: 1100

Answers (3)

Chris McClellan
Chris McClellan

Reputation: 1105

if (in_array(345, $array)) {
    return true;
} else {
    return false;
}

didn't see that you wanted to do this 1000 times per number. use a database.

Use a db like this:

$result = mysql_query("SELECT * WHERE number={$number}", $link);
$x = (mysql_num_rows($result) > 0  ? mysql_num_rows($result) : false );

Upvotes: 2

Roger W.
Roger W.

Reputation: 165

This is more of a computer science problem than a PHP one. I would recommend looking into "binary search" or "binary trees". If you google around, you might even find an existing implementation.

Upvotes: 2

Matthew
Matthew

Reputation: 48304

The simplest thing is to flip the array around (see array_flip) and use isset($array[$key]). That uses a hash lookup instead of a search, so it's much faster.

Other than that, try using a database or some more optimal way of dealing with large datasets.

Upvotes: 8

Related Questions