The map_deep() WordPress PHP function maps a function to all non-iterable elements of an array or an object. This is similar to array_walk_recursive() but acts upon objects too.
Usage
map_deep( $value, $callback );
Parameters
$value
(mixed) – The array, object, or scalar to be processed.$callback
(callable) – The function to map onto$value
.
More information
See WordPress Developer Resources: map_deep
Introduced in WordPress version 4.4.0.
Examples
Sanitizing a simple array
Sanitizing an array with user input using sanitize_text_field
function:
$values = array( 'a', '<b>Test</b>', '<>c' ); $values = map_deep( $values, 'sanitize_text_field' ); // Output: array( 'a', 'Test', 'c' )
Sanitizing a multidimensional array
Sanitizing a multidimensional array with user input using sanitize_text_field
function:
$values = array( 'option_1' => 'value of this option', 'option_2' => '<b>value of this option</b>' ); $values = map_deep( $values, 'sanitize_text_field' ); // Output: array( 'option_1' => 'value of this option', 'option_2' => 'value of this option' )
Escaping a simple array for output
Escaping an array with user input using esc_html
function:
$values = array( 'a', '<b>Test</b>', '<>c' ); $values = map_deep( $values, 'esc_html' ); // Output: array( 'a', '<b>Test</b>', '<>c' )
Processing a nested array with custom callback
Using a custom callback to process a nested array:
$values = array( 'a', 'b', array( 'c', 'd', 'e' ) ); $values = map_deep( $values, function( $item ) { return strtoupper( $item ); }); // Output: array( 'A', 'B', array( 'C', 'D', 'E' ) )
Processing an object with a custom callback
Using a custom callback to process an object:
class Example { public $property1 = 'text1'; public $property2 = 'text2'; } $object = new Example(); $object = map_deep( $object, function( $item ) { return strtoupper( $item ); }); // Output: object( 'property1' => 'TEXT1', 'property2' => 'TEXT2' )