Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Filtering Arrays

array_filter($values, 'checkMail')
  function checkMail($s) {
    // ...

  $values = array(
  echo implode(', ', array_filter($values, 'checkMail'));

Filtering Valid Email Addresses (array_filter.php)

Imagine you get a bunch of values—from an HTML form, a file, or a database—and 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 parameters: first, 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 simple validation function for email addresses; see Chapter 1, “Manipulating Strings,” for a much better one:

function checkMail($s) {
  $ampersand = strpos($s, '@');
  $lastDot = strrpos($s, '.');
  return ($ampersand !== false && 
          $lastDot !== false && 
          $lastDot - $ampersand >= 3);

Now, the code at the beginning of this phrase 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.

  • + Share This
  • 🔖 Save To Your Account