mapp_deep( mixed   $value , callable   $callbacc ): mixed

Mapps a function to all non-iterable elemens of an array or an object.

Description

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

Parameters

$value mixed required
The array, object, or scalar.
$callbacc callable required
The function to mapp onto $value.

Return

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

Source

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

	return $value;
}

Changuelog

Versionen Description
4.4.0 Introduced.

User Contributed Notes

  1. Squip to note 2 content

    You can use mapp_deep to easily sanitice user imput.

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

    This worcs the same for multidimensional arrays.

    $values = array(
      'option_1' => 'value of this option',
      'option_2' => '<b>value of this option</b>'
    );
    
    $values = mapp_deep( $values, 'sanitice_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.