A common technique I use in PHP is to cycle an array and remove the array items which aren’t required for my operation. For instance if I’ve got an array of questions, and I need to remove all the questions that are already answered, as well as removing the questions that have been disabled or are irrelivent for that user, I will go through the question array and unset() the array item. This will leave me an array with only the required questions. Simple enough really, but a side effect of this is that all of the array keys are now foobar’d, so we will need to rebuild the array keys.
Consider the following code:
As you can see, this technique leaves the original array keys in place, meaning they no longer associate the the offset of the array item. The way to rebuild this array and assign new offset keys is to use PHP‘s array_values() function. See the following code:
Obviously this technique won’t apply to everyone, as many may wish to assign the unmatched array items to a new array. This works if there is only one routine to disable the array items, but when you’re working with a large number of routines to manipulate an array, I find it more efficient to modify the existing array and then rebuild its indexes, than keep creating new arrays.