wp_array_slice_assoc()
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( $input_array, $keys );
- $input_array(array) (required)
- The original array.
- $keys(array) (required)
- The list of keys.
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.7.1
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; }