- Accessing All Elements of Numeric Arrays
- Accessing All Elements of Associative Arrays
- Accessing All Array Elements in Nested Arrays
- Turning an Array into Variables
- Converting Strings to Arrays
- Converting Arrays to Strings
- Sorting Arrays Alphabetically
- Sorting Associative Arrays Alphabetically
- Sorting Nested Arrays
- Sorting Nested Associative Arrays
- Sorting IP Addresses (as a Human Would)
- Sorting Anything
- Sorting with Foreign Languages
- Applying an Effect to All Array Elements
- Filtering Arrays
- Getting Random Elements Out of Arrays
- Making Objects Behave Like Arrays
Filtering Arrays
array_filter($values, 'checkMail')
<?php function checkMail($s) { // ... } $values = array( 'valid@email.tld', 'invalid@email', 'also@i.nvalid', 'also@val.id' ); 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.