Forum Moderators: coopster
I've got this array of strings, you see, and I need to keep the ones which contain any of a number of other strings. I'm thinking, I need something like:
$needlearray = ('peanut', 'butter', 'jelly');
foreach($haystackarray as $k=>$v){
if(strpos($v, $needlearray)) $newarray[] = $v;
}
Instead, I think I'm looking at either a double loop, looping through the haystackarray inside the needle array, or else going through the haystack array like:
foreach($haystackarray as $k=>$v){
if(preg_match('#(peanut¦butter¦jelly)#', $v) $newarray[] = $v;
}
Looping through a processor-eating regex to do this easy thing just seems atrocious. Someone give this worthless soggy bag of grey wrinkles a kick in the right direction please.
I would time the 2 and take the quicker one but I would think the double loop should be faster. It may depend on the number of elements in each array though.
having your needle bit compare a single array element with all needles, then onto the next. It might speed it up a bit if it is a native function.
I was also thinking of ways for array intersects and all that but it doesn't work with substrings that I could think of.
Regarding array intersects, one aweful-aweful klugey approach I'd thought of just uses PHP's own function print_r which deals nicely with (infinite) recursion (forget as of which version - I remember back 'round 4.06 either print_r or var_dump would crash if you used $GLOBALS as an argument, I'm hoping 4.10 got this solved, that's my backwards-compat goal so can't use 5). If you really, absolutely, necessarily must search the GLOBAL variables for something, you can use a buffered print_r (or print_r($var, true) as of 4.3) and PHP takes care of recursion and other problems for you - you then, of course, are straddled with the nasty task of parsing all this output, to find the parent elements, but at least only in those cases where the searchstring has actually been found (if it's not a situation where you need to find lots of multiple instances). In my case, only partially parsing the output would probably be enough, let the user figure the rest out.