I have a large array in PHP.
It contains strings that are split into a kind of categories using underscores:
category1_property
category1_category2_category3
category2_category3_category4_category5
I have a function named
array get_values($prefix)
that returns all values of the array that start with a given prefix, e.g.
get_values("category2_category3_");
This function foreach()es through the whole array every time, collecting all strings that start with the prefix, i.e. a simple
foreach ($my_array as $line)
if (substr($line, 0, strlen($prefix)) == $prefix))
array_push ($result, $line);
I feel bad doing that performance-wise, especially seeing that this operation is performed dozens of times per request.
Does anybody know a way to speed this up without having to resort to a whole different way of storing the data?
Using a database might be fast and clever but I would like to avoid that. The data comes from a file and I can't port it to a database.
Pre-sorting or splitting the construct into a multi-dimensional array or an object is not an option, because I sometimes need to query for parts of a category name (e.g. "category1_ca*")
Thanks in advance for any input.