RetroCode UK

Published Date Jan 23, 2013 Reading Time ~2 minutes RSS Feed Web Development

Processing Multiple Strings in an Array

IMPORTANT: This content is over 1 year old, and may now be obsolete, irrelevant and/or no longer accurate.

This post concentrates on filtering values from a one-dimensional array.

There are a lot of really useful functions in PHP, and it's almost impossible to remember them all.  Array functions are no exception, and as with PHP functions generally the little inconsistencies are just waiting there to catch you out.

Anyway, I just wanted to mention the difference between array_walk and array_map, and why array_map is particularly useful.

Firstly, array_map

The array_map function is really useful as it uses a callable function as the first parameter, and assigns the result of the function as it iterates through the array while passing each value of the array to the function in turn.  This means that it works with many standard PHP functions that take one parameter and returns the modified parameter as the result.

Take the following as an example:

$values = array(' test ',' banana ','apple ');
$trimmed_array = array_map(trim,$values);

The result would be:

array(3) { [0]=> string(4) "test" [1]=> string(6) "banana" [2]=> string(5) "apple" }

Similarly, you can use the function to sanitize an array of integers:

$values = array(' test123 ','12','14.6');
$array = array_map(intval,$values);

The result of that would be:

array(3) { [0]=> int(0) [1]=> int(12) [2]=> int(14) }

Notice that any non-valid numbers are evaluated as zero.  Proper sanitization of strings cannot be emphasised enough, especially if you are using values like this to concatenate into an SQL query or something.

Like I mentioned earlier, there are many functions that work well with array_map.  Here are more some examples: strtoupper, strip_tags, html, htmlentities, etc.

Why use array_walk

The function array_walk is subtly different in that it takes similar parameters (single dimension array, and a callable function), but it only is effective when the function modifies the value by reference. This is significant because you cannot use it to sanitize arrays just by referring to functions like intval and strip_tags.  However, there is one benefit to using array_walk, and that is you can add an additional optional parameter to send to the callable function.