foreach vs array_filter

The problem:

Given an array of numbers, create a new array containing only the odd numbers from the original.

There are two ways you can approach this problem. Let’s look at a foreach loop first:

  1. Set up a variable to hold the new array of odd numbers.
  2. Loop over the original array
  3. Test each value – if it is not evenly divisible, push it onto the odd number array

This way of approaching the problem works, and there is nothing wrong with doing it this way. However, there is a better way.

The array_filter function automatically iterates over all the elements of the array. One by one, each item in the array is passed to the callback function. The array_filter function will return an array, and expects the callback to return true or false for each item. True means that item will be placed into the array that array_filter returns. False means that item won’t be in the returned array.

Inside the callback in this example, each item is tested to see if it is even, and then that result is negated because we actually want to test for odd.

The callback does not have to be inline.  You can call an external function, like this:

This is nice because you can separate concerns. You can now refactor the isOdd method if you want to, and it will still work.

Sample output: (note that array keys are preserved)


So, what about associative arrays?

Let’s first adapt the original foreach solution:

This will output:

Let’s try it with the array_filter function:

This will be the output:

Notice how it returns an associative array. This is much better than the previous way, which had a key of [0].