Filtering Arrays


 array_filter($values, 'checkMail')) 


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 Chapter 1, "Manipulating Strings," for a discussion of this topic).

Filtering Valid Email Addresses (array_filter.php)
 <?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 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.




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net