How to Apply a Function to Each Value in an Array CodeUnit 23 MAR 2010

Sometimes you wish to apply a certain function, be it a built in PHP function or one of your own creations, to each and every value within a particular array. Now doing this is of course as easy as writing a loop to iterate through an array, perform the function on each retrieved value and then save the updated value back into the array.

Easy, but unnecessary.

You see, PHP comes bundled with a great little function called array_map() that is used to apply a callback function to each and every value contained in the supplied array.

So for example if we wanted to throw strip_tags against an array’s contents, it would look something like this:

$original = array('


', 'Bold'); $new = array_map('strip_tags', $original);

As you would expect, the result of this would be an array containing the words Paragraph and Bold, devoid of all their HTML markup.


Related Link:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.