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);
}
}
}