wp_array_slice_assoc()WP 3.1.0

Extract a slice of an array, given a list of keys.

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.

Return

Array. The array slice.

Usage

wp_array_slice_assoc( $array, $keys );
$array(array) (required)
The original array.
$keys(array) (required)
The list of keys.

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
)
*/
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.

Code of wp_array_slice_assoc() WP 5.9.3

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

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

	return $slice;
}