Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array problem

Tags:

arrays

php

search

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?

like image 492
James Avatar asked Apr 16 '26 23:04

James


1 Answers

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.

like image 112
Matthew Avatar answered Apr 19 '26 11:04

Matthew