Skip to content

array_filter_with_keys

Tonya Mork edited this page Mar 12, 2017 · 2 revisions

The array_filter_with_keys() function filters an array by passing each key => value part to the given callback. The callback is responsible for the filtering process. If the callback returns true, then the element is included in the returned dataset; else, it's excluded.

Why Not Just Use array_filter?

PHP 5.6.0 gave us the ability to pass keys to the function array_filter by specifying the third parameter as ARRAY_FILTER_USE_BOTH. That capability is not available from PHP before version 5.6.0.

Therefore, our function array_filter_with_keys() provides the same functionality for earlier versions of PHP.

Syntax

array array_filter_with_keys( 
     array $subjectArray, 
     [ callable $filteringCallback ]
);

Where:

$subjectArray is the array to work on

$filteringCallback (optional) is a closure, function, or method that filters the elements. When you don't pass it a callback, this function strips all elements where the value is falsey.

Example - Remove Falseys

$dataSet  = array(
	0 => 'foo',
	1 => false,
	2 => - 1,
	3 => null,
	4 => '',
	5 => array(),
	6 => 0,
	7 => '0',
	8 => array(
		'foo',
		'bar',
	),
);

$results = array_filter_with_keys( $dataSet );
/**
 * Returns:
 * 
 *  array(
 *	    0 => 'foo',
 *	    2 => - 1,
 *	    8 => array(
 *		    'foo',
 *		    'bar',
 *	    ),
 *  );
 */

Example - Is Even

$dataSet  = array(
	'a' => 1,
	'b' => 2,
	'c' => 3,
	'd' => 4,
	'e' => 5,
	'f' => 6,
	'g' => 7,
	'h' => 8,
);

$evens = array_filter_with_keys( $dataSet, function ( $key, $value ) {
	return $value % 2 === 0;
} ) );

/**
 * Returns:
 *
 *  array(
 *	    'b' => 2,
 *	    'd' => 4,
 *	    'f' => 6,
 *	    'h' => 8,
 *  );
 */

Using the same dataset, you can pass any type of callable callback:

function isEvenNumber( $key, $value ) {
	return $value % 2 === 0;
}

$evens = array_filter_with_keys( $dataSet, 'isEvenNumber' );

// or if in a namespace

$evens = array_filter_with_keys( $dataSet, __NAMESPACE__ . '\isEvenNumber' );

« Back to Array API

Clone this wiki locally