1

I'm creating a function that "cleans" data (escapes html to avoid xss) from the database before sending it to the views. All the data is passed on in 1 array. This arrays contains variables and arrays that contain other variables and arrays, and so on.

This is what I have now, it works, but it just doesn't look right. Is there any way to avoid going through a new foreach for every array inside an array?

public function clean_output(&$data)
{
  if(!is_array($data))
  {
    $data = htmlspecialchars($data);
  }
  else
  {
    foreach($data as &$data_1)
    {
      if(!is_array($data_1))
      {
        $data_1 = htmlspecialchars($data_1);
      }
      else
      {
        foreach($data_1 as &$data_2)
        {
          if(!is_array($data_2))
          {
            $data_2 = htmlspecialchars($data_2);
          }
          else
          {
            foreach($data_2 as &$data_3)
            {
              $data_3 = htmlspecialchars($data_3);
            }
          }
        }
      }
    }
  }
}

Thanks to Antoine, I got a new function. Suggestions still welcome offcourse!

public function clean_output(&$data)
    {
      if(!is_array($data))
      {
        $data = htmlspecialchars($data);
      }
      else
      {
        foreach($data as &$data_1)
        {
          $this->clean_output($data_1);
        }
      }
    }

1 Answer 1

2

You must use recursive function ! http://www.elated.com/articles/php-recursive-functions/

Sign up to request clarification or add additional context in comments.

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.