UltraMega Blog
3Nov/090

PHP: Process Array Items With array_map

Let's say you want to run a function on each item in an array. For example, you want to run strip_tags() on all $_POST data. One way to accomplish that is to use a foreach loop and reassign each array element manually, but there's a function for that. The array_map function accepts the name of a function and an array or arrays to run the function on.

So to accomplish our simple example, this is all it takes:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('strip_tags', $original);
 
// $new is now array('Paragraph', 'Bold');

You can supply any function, including any you define for more advanced use:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('clean_input', $original);
 
function clean_input($value)
{
    return strip_tags($value, '<p>'); // allow p tags
}
 
// $new is now array('<p>Paragraph</p>', 'Bold');

The array_map function is a powerful utility when it comes to working with arrays. You can do things in one line that would otherwise require loops and other complex structures. The examples here are just very basic, but are handy for many everyday tasks. Check the examples in the PHP documentation for other tricks array_map can do.