0

How can I iterate a multidimensional array and filter on string nodes? I'm trying to create an easy way to sanitize data coming into my application via POST and think this would be really handy.

3

2 Answers 2

5

You can use a recursive function to traverse the array and filter its string components. For example:

function doFilter($arr) {
    foreach ($arr as $key => $value) {
        if (is_string($value)) {
            $arr[$Key] = sanitize($value);
        } else if (is_array($value)) {
            $arr[$key] = doFilter($value);
        }
    }
    return $arr;
}

function sanitize($str) {
    // Perform necessary steps to sanitize $str
    return $str;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use Recursion

function sanitizePost($post) {
        if (is_array($post)){
            foreach ($post as $k => $p) {
                $post[$k] = sanitizePost($p);
            }
        } else {
            $post = sanatizeStringFunction($post); // may be use regex or something
        }

        return $post;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.