Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sanitize multi dimensional PHP arrays
<?php
// Only the first parameter is necessary. The other two are there because of the recursion :)
function sanitizeArray (array $array, array &$output = [], $breakpoint = 0) {
foreach($array as $key => $val){
if(++$breakpoint > 1000){
return false;
}
if(is_array($val)){
$output[htmlspecialchars($key)] = sanitizeArray($val, $output, $breakpoint);
}else{
$output[htmlspecialchars($key)] = htmlspecialchars($val);
}
}
return $output;
}
<?php
// Only the first parameter is necessary. The other one is there because of the recursion :)
function sanitizeArray (array $array, array &$output = []) {
foreach($array as $key => $val){
if(is_array($val)){
$output[htmlspecialchars($key)] = sanitizeArray($val, $output);
}else{
$output[htmlspecialchars($key)] = htmlspecialchars($val);
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment