WordPress at a glance

map_deep() WP 4.4.0

Applies the specified function to the values of the passed array/object/string/number. It's a recursive function.

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

✈ 1 time = 0.000031s = very fast | 50000 times = 0.17s = very fast

No Hooks.

Return

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

Usage

map_deep( $value, $callback );
$value(mixed) (required)
The array, object, or scalar.
$callback(callable) (required)
The function to map onto $value.

Examples

#1 Use the function for all elements of an array.

// a callback
function myint( $val ){
	if( $val === 1 ) return 111;
	return (int) $val;
}

$val = array( 1, '2 apples', 'and a pear' );

$val = map_deep( $val, 'myint' ); // 111
/*
Array
(
	[0] => 111
	[1] => 2
	[2] => 0
)
*/

#2 If you pass a string to map_deep()

If we know in advance that we get a string, then, of course, we can just apply the function to that string.

But, if we do not know in advance what type of value will come, it makes sense to pass the resulting value in map_deep(). In this case, if the function receives a string, then nothing bad will happen — the function will process passed value and return the processed value of the received string:

// myint() функция из прошлого примера...

// обработаем строку
$val = '2 яблока';
echo map_deep( $val, 'myint' ); //> 2

Code of map deep: wp-includes/formatting.php WP 5.2.1

<?php
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;
}

Related Functions

From category: Helper Functions

No comments
    Hello, !     Log In . Register