map_deep( mixed $value, callable $callback ): mixed

Maps a function to all non-iterable elements of an array or an object.

Description

This is similar to array_walk_recursive() but acts upon objects too.

Parameters

$valuemixedrequired
The array, object, or scalar.
$callbackcallablerequired
The function to map onto $value.

Return

mixed The value with the callback applied to all non-arrays and non-objects inside it.

Source

function map_deep( $value, $callback ) {
	if ( is_array( $value ) ) {
		foreach ( $value as $index => $item ) {
			$value[ $index ] = map_deep( $item, $callback );
		}
	} elseif ( is_object( $value ) ) {
		$object_vars = get_object_vars( $value );
		foreach ( $object_vars as $property_name => $property_value ) {
			$value->$property_name = map_deep( $property_value, $callback );
		}
	} else {
		$value = call_user_func( $callback, $value );
	}

	return $value;
}

Changelog

VersionDescription
4.4.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can use map_deep to easily sanitize user input.

    $values = array( 'a', '<b>Test</b>', '<>c' );
    
    $values = map_deep( $values, 'sanitize_text_field' );
    
    // Output: array(
    //    "a",
    //    "Test",
    //    "c",
    // )

    This works the same for multidimensional arrays.

    $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",
    // )

You must log in before being able to contribute a note or feedback.