PHP

Recursively Apply Callback to All Multi-Dimensional Array Elements

Efficiently apply a user-defined function to every scalar value within a deeply nested PHP array using `array_walk_recursive` for transformations.

function sanitize_array_data(array &$array): void {
    array_walk_recursive($array, function (&$item, $key) {
        if (is_string($item)) {
            $item = trim(strip_tags($item)); // Example: trim and strip HTML tags
            // $item = htmlspecialchars($item, ENT_QUOTES, 'UTF-8'); // Example: escape HTML
        }
    });
}

$data = [
    'user_name' => '  John Doe  ',
    'email' => '[email protected]',
    'address' => [
        'street' => '123 Main St <script>alert("xss")</script>',
        'city' => 'Anytown',
        'zip' => '12345'
    ],
    'preferences' => [
        'theme' => 'dark',
        'notifications' => true,
        'tags' => ['  PHP  ', '  Web  Development  ']
    ]
];

echo "Original Data:
";
print_r($data);

sanitize_array_data($data);

echo "Sanitized Data:
";
print_r($data);

/* Expected Sanitized Output (truncated):
Array
(
    [user_name] => John Doe
    [email] => [email protected]
    [address] => Array
        (
            [street] => 123 Main St
            [city] => Anytown
            [zip] => 12345
        )

    [preferences] => Array
        (
            [theme] => dark
            [notifications] => 1
            [tags] => Array
                (
                    [0] => PHP
                    [1] => Web Development
                )

        )

)
*/
How it works: The `sanitize_array_data` function demonstrates how to use `array_walk_recursive` to apply a callback function to every scalar element within a multi-dimensional array. This is incredibly useful for tasks like data sanitization (e.g., trimming whitespace, stripping HTML tags, or escaping characters), type conversion, or any other transformation that needs to be performed on all deep-seated values. The callback receives a reference to the item, allowing for in-place modification of the original array, making it an efficient way to process complex nested data structures.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs