PHP

Filtering Arrays

array_filter($values, 'checkMail'))

The array_filter function

array array_filter ( array $input [, callable $callback = "" ] )

This function filters the array elements using a callback function. array_filter returns the processed/filtered array and accepts two parameters:

  1. input an array

  2. callback a function

Imagine you get a bunch of valuesfrom an HTML form, a file, or a databaseand want to select which of these values are actually usable and which are not. You could again call for, foreach, or while and find out what is interesting, or you can let PHP do most of the work. In the latter case, get acquainted with the function array_filter(). This one takes two parametersfirst, the array to be filtered and, second, a function name (as a string) that checks whether an array element is good. This validation function returns true upon success and false otherwise. The following is a very simplistic validation function for email addresses (see tutorial 1, "Manipulating Strings," for a discussion of this topic).

Filtering Valid Email Addresses

<?php
function checkMail($s) {
  $ampersand = strpos($s, '@');
  $lastDot = strrpos($s, '.');
  return ($ampersand !== false &&
          $lastDot !== false &&
          $lastDot - $ampersand >= 3);
}
  $values = array(
    'valid@email.tld',
    'invalid@email',
    'also@i.nvalid',
    'also@val.id'
  );
  echo implode(', ', array_filter($values,
    'checkMail'));
?>

Now, the code at the beginning of This calls array_filter(), so that only (syntactically) valid email addresses are left.

As you would expect, the code just prints out the two valid email addresses.

by BrainBellupdated
Advertisement: