wp_array_slice_assoc()
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:
- array_intersect_key( $array1, $array2 ) — leaves elements of the array whose keys match the keys of the second array.
- $array = array_intersect( $array1, $array2 ) — leaves elements of the array whose values match the values of the second array.
- $array = array_intersect_assoc( $array1, $array2 ) — leaves elements of the array whose indexes and values match the indexes and values of the second array.
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:
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
#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 ) );
#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 ) */
#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() 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;
}