note 126689 added to function.array-map

From: Date: Thu, 16 Dec 2021 20:15:35 +0000
Subject: note 126689 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-217378@lists.php.net to get a copy of this message
/** * Function which recursively applies a callback to all values and also its * keys, and returns the resulting array copy with the updated keys and * values. * PHP's built-in function array_walk_recursive() only applies the passed * callback to the array values, not the keys, so this function simply applies * the callback to the keys too (hence the need of working with a copy, * as also updating the keys would lead to reference loss of the original * array). I needed something like this, hence my idea of sharing it here. * * @param callable $func callback which takes one parameter (value * or key to be updated) and returns its * updated value * * @param array $arr array of which keys and values shall be * get updated */ function array_map_recursive( callable $func, array $arr ) { // Initiate copied array which will hold all updated keys + values $result = []; // Iterate through the key-value pairs of the array foreach ( $arr as $key => $value ) { // Apply the callback to the key to create the updated key value $updated_key = $func( $key ); // If the iterated value is not an array, that means we have reached the // deepest array level for the iterated key, so in that case, assign // the updated value to the updated key value in the final output array if ( ! is_array( $value ) ) { $result[$updated_key] = $func( $value ); } else { // If the iterated value is an array, call the function recursively, // By taking the currently iterated value as the $arr argument $result[$updated_key] = array_map_recursive( $func, $arr[$key] ); } } // end of iteration through k-v pairs // And at the very end, return the generated result set return $result; } // end of array_map_recursive() function definition ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 178.39.48.213) ---- Manual Page -- https://php.net/manual/en/function.array-map.php Edit -- https://main.php.net/note/edit/126689 Del: integrated -- https://main.php.net/note/delete/126689/integrated Del: useless -- https://main.php.net/note/delete/126689/useless Del: bad code -- https://main.php.net/note/delete/126689/bad+code Del: spam -- https://main.php.net/note/delete/126689/spam Del: non-english -- https://main.php.net/note/delete/126689/non-english Del: in docs -- https://main.php.net/note/delete/126689/in+docs Del: other reasons-- https://main.php.net/note/delete/126689 Reject -- https://main.php.net/note/reject/126689 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217378) next »