Use this function to remove certain elements from an array. The elements to be removed depend on the function you pass them through.

Name the function and each value for which it returns true will be included in the result array. Keys are preserved.

User defined functions or PHP functions work here. If you don’t name a function, the value will be included if it equates to true when cast to a boolean.

$arr = array( 'a' => 'apple',
              'b' => 'banana',
              'c' => 'carrot',
              'd' => 'durian',
              'e' => 'eggplant',
              'f' => 'fennel' );
 
function six_letters( $word ) {
  return 6 == strlen( $word );
}
 
$new = array_filter( $arr, 'six_letters' );
/*
array (
  'b' => 'banana',
  'c' => 'carrot',
  'd' => 'durian',
  'f' => 'fennel'
)
*/
 
// same as doing
$new = array();
foreach( $arr as $k => $v ) {
  if( 6 == strlen( $v ) ) {
    $new[$k] = $v;
  }
}

Here we use some of PHP’s built in functions is_numeric() and is_bool(). Finally, we use array_filter() without specifying a callback function which will remove those values which cast to boolean false.

$arr = array( 'a' => 17,
              'b' => false,
              'c' => true,
              'd' => '99 luftballons',
              'e' => null );
 
$new = array_filter( $arr, 'is_numeric' );
/*
array (
  'a' => 17
)
*/
 
$new = array_filter( $arr, 'is_bool' );
/*
array (
  'b' => false,
  'c' => true
)
*/
 
$new = array_filter( $arr );
/*
array (
  'a' => 17,
  'c' => true,
  'd' => '99 luftballons'
)
*/