Categories
PHP

array_filter(): Filtering Arrays

The array_filter() function filters the elements of an array by applying a callback function to each element to decide whether it appears in the output array. The callback function returns true upon success and false otherwise.

<?php
 //Syntax
 array_filter(array $array,
              ?callable $callback = null, 
              int $mode = 0): array

The array_filter() function returns the filtered array and accepts three parameters:

  1. $array – an input array
  2. $callback– (optional) a function, if not supplied, all empty entries of the array will be removed.
  3. $mode – (optional) by default pass value as the only argument to the callback.
    Use the ARRAY_FILTER_USE_KEY flag to pass key instead.
    Use the ARRAY_FILTER_USE_BOTH flag to pass both value and key.

Remove empty array elements

PHP considers a value empty when converting to boolean type returns false. The following values are considered empty:

  1. FALSE
  2. 0, '0', "0", 0.0, or -0.0
  3. Empty string '' and ""
  4. Empty array (array with zero elements) array() or []
  5. NULL or undefined variables

When you use the array_filter function without a callback function it removes all the values which PHP considered as empty:

Example: Remove all empty values with array_filter()

<?php
 $a = [1,2, 0,'0',0.0,false,null,'',[],4,5,"" ];
 $b = array_filter($a); 
 print_r($b);
/* Prints: 
Array
(
    [0] => 1
    [1] => 2
    [9] => 4
    [10] => 5
)*/

Example: Remove empty strings from an array with array_filter()

<?php
 $a = ['a', '  ', null, 'b',  "  ", 'c', 0, false];
 $b = array_filter($a, 'filter_empty_strings');

 function filter_empty_strings($v){
  if (is_string($v)){
   return '' !== trim($v);
  }
  return true;
 }

 var_dump($b);
/* prints: 
array(6) {
  [0]=> string(1) "a"
  [2]=> NULL
  [3]=> string(1) "b"
  [5]=> string(1) "c"
  [6]=> int(0)
  [7]=> bool(false)
}*/

Example: Validate a list of email addresses with array_filter()

<?php
 function validateEmailAddress($v) {
  return filter_var($v, FILTER_VALIDATE_EMAIL);
 }
 $list = [
    'admin@brainbell.com',
    'admin@brainbell_com',
    'info[at]brainbell.com',
    'info@brainbell.com'
    ];
 $validList = array_filter($list, 'validateEmailAddress');
 print_r($validList);
 
 /*Prints:
Array
(
    [0] => admin@brainbell.com
    [3] => info@brainbell.com
)*/

The array_filter() filter out the invalid addresses so that only (syntactically) valid email addresses are left. As you would expect, the code just prints out the two valid email addresses.

Note: The array_filter() function keeps the keys/values association intact. If you need to reindex the array after removing the empty elements, use: array_values() function.

<?php
 /*follow previous example code*/
 $validList = array_values(
               array_filter($list, 'validateEmailAddress')
              );
 print_r($validList);
/*Prints:
Array
(
    [0] => admin@brainbell.com
    [1] => info@brainbell.com
)*/

Filter arrays by indexed key

Use the ARRAY_FILTER_USE_KEY flag if you want to deal with array indexes instead of the values.

<?php
 function filterKey($v) {
  return $v !== 1;
 }
 $a = ['a','b','c'];
 $f = array_filter($a, 'filterKey', 
                   ARRAY_FILTER_USE_KEY );
 
 print_r($f);
 /*
Array
(
    [0] => a
    [2] => c
)*/

Filter arrays by keys and values

Use the ARRAY_FILTER_USE_BOTH flag if you want to deal with both values and keys.

<?php
 function filterBoth($value, $key) {
  return !($key === 1 && $value === 'b');
 }

 $a = ['a','b','c'];
 $f = array_filter($a, 'filterBoth', 
                   ARRAY_FILTER_USE_BOTH );
 
 print_r($f);
 /*
Array
(
    [0] => a
    [2] => c
)*/

Working with arrays:

  1. Creating Arrays
  2. Array Iteration
  3. Array Internal Pointers
  4. Explode and Implode Functions
  5. Count Array Elements, Find Min and Max Values
  6. Search values and keys in arrays
  7. Filter array elements using array_filter()
  8. Modify array elements using array_map() and array_walk()
  9. Split, tokenize, and iterate a string
  10. Convert a delimited string into an array
  11. Sorting arrays