Applying an Effect to All Array Elements

$a = array_map('sanitize', $a);

Sometimes, data in an array has to be preprocessed before it can be used. In Interacting with Web Forms, you will see how data coming from the user via HTML forms can be sanitized before it is used. To do so, every array element must be touched.

Applying htmlspecialchars() to All Elements of an Array
  function sanitize($s) {
    return htmlspecialchars($s);
  $a = array('harmless', '<bad>', '>>click here!<<');
  $a = array_map('sanitize', $a);
  echo implode(' ', $a);

However, it is not required that you do a cumbersome for/foreach/while loop; PHP offers built-in functionality for this. The first possibility is to use array_map(). This takes an array (second parameter) and submits every element in that array to a callback function (first parameter, as a string). At the end, the array is returned, with all of the elements replaced by the associated return values of the callback function.

In the preceding listing, all values in the array are converted into HTML using htmlspecialchars().

If, however, the array turns out to be a nested one, the tactic has to be changed a little. Then a recursive function can be used. If an array element is a string, it is HTML-encoded. If it's an array, the recursive function calls itself on that array. The following code implements this, and Figure 2.6 shows the result.

Recursively Applying htmlspecialchars() to All Elements of a Nested Array
  function sanitize_recursive($s) {
    if (is_array($s)) {
      return(array_map('sanitize_recursive', $s);
    } else {
      return htmlspecialchars($s);
  $a = array(
    'harmless' =>
      array('no', 'problem'),
    'harmful' =>
      array('<bad>', '> <worse> <<-')
  $a = sanitize_recursive($a);
  echo '<pre>' . print_r($a, true) . '</pre>';

The nested arrays have been HTML-encoded.

Another function that behaves similarly is array_walk(). This one also applies a function to every element of an array; however, it also allows you to provide a parameter for this function call. In the following code, this is used to print out all elements of an array. A parameter is passeda counter. Because it is passed by reference, increasing this counter by 1 within the function leads to a sequence of numbers.

Printing Array Elements Using array_walk() and a Counter Passed by Reference
  function printElement($s, &$i) {
    printf('%d: %s<br />', $i,
  $i = 1;
  $a = array('one', 'two', 'three', 'four');
  $a = array_walk($a, 'printElement', $i);

Running the preceding code shows the following:

0: one
1: two
2: three
3: four

by BrainBellupdated