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('

Paragraph

', '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.

Nice!

Related Link: http://www.php.net/manual/en/function.array-map.php

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.