Consider three options:
- grep: Iterates through the haystack list and returns a new needles list comprised of elements from the haystack that meet the criteria you set forth. At the outset, this may seem expensive; it requires more memory than in-place editing, for example. But computationally it's a linear approach.
- foreach and push onto a new array: This is a very similar approach to grep, but might feel more comfortable in cases where the criteria are not trivial. Again, you're walking through the haystack and creating a new list of found needles.
- foreach and splice: Probably most memory efficient, but think of what's going on from a computational standpoint: Locate a delete line, delete it, then shift all remaining elements down one. Locate another delete line, delete it, then shift all remaining elements down one again, and so on. Worst case is deleting every line, starting with the first. In such a case, the computational complexity is a little better than quadratic. Each time you find a needle, you have to move every remaining piece of hay over one position.
If you have the ability to throw memory at the problem, I would tend to favor the linear solution provided by grep or by foreach combined with push.