wp_array_slice_assoc()WP 3.1.0

Leaves elements from the first array whose keys (indexes) match the values of the second array.

Does the same as array_intersect_key( $array1, $array2 ), only compares the keys of the first array with the values of the second.

In PHP, there are similar functions:

For the opposite calculation, when you need to leave only those elements in the first array that are not in the second array, use PHP functions:

1 time — 0.000017 sec (very fast) | 50000 times — 0.08 sec (speed of light) | PHP 7.0.4, WP 4.4.2

No Hooks.

Returns

Array. A piece of the passed array with the required elements.

Usage

wp_array_slice_assoc( $array, $keys );
$array(array) (required)
The original array from which elements need to be obtained.
$keys(array) (required)
A list of keys from $array that need to be retained.

Examples

0

#1 Let's leave only the necessary elements from the passed array

This example shows how the function works. We have an array and we need to process it and leave only the specified elements in it by the key.

$array = [
	'one' => '1one',
	'two' => '2two',
	'three' => '3three',
];

$needed_keys = array( 'one', 'three' );
$filtered = wp_array_slice_assoc( $array, $needed_keys );

print_r( $filtered );

/* we get
Array
(
	[one] => 1one
	[three] => 3three
)
*/

The same can be done in PHP via array_intersect_key():

$filtered = array_intersect_key( $array, array_flip( $needed_keys ) );
0

#2 Example of using array_intersect()

Leaves elements from the first array whose values coincide with the values of the second array.

I.e. only the values are compared

$array = [
	'one' => '1one',
	'two' => '2two',
	'three' => '3three',
];

$needed_keys = array( ''=>'1one', 'one'=>'' );
$filtered = array_intersect( $array, $needed_keys );

print_r( $filtered );

/* we get
Array
(
	[one] => 1one
)
*/
0

#3 Example of operation array_intersect_assoc()

Leaves elements from the first array, whose values and indexes coincide with the values and indexes of the second array.

$array = [
	'one' => 'foo',
	'two' => 'bar',
	'three' => 'baz',
];

$needed_keys = array( 'one'=>'foo', 'three' );
$filtered = array_intersect_assoc( $array, $needed_keys );

print_r( $filtered );

/* we get:
Array
(
	[one] => foo
)
*/

Changelog

Since 3.1.0 Introduced.

wp_array_slice_assoc() code WP 6.9

function wp_array_slice_assoc( $input_array, $keys ) {
	$slice = array();

	foreach ( $keys as $key ) {
		if ( isset( $input_array[ $key ] ) ) {
			$slice[ $key ] = $input_array[ $key ];
		}
	}

	return $slice;
}