Skip to content

Instantly share code, notes, and snippets.

@bragle
Created May 11, 2019 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bragle/04cedaecb4747e7e7b32ca255ec1e1aa to your computer and use it in GitHub Desktop.
Save bragle/04cedaecb4747e7e7b32ca255ec1e1aa to your computer and use it in GitHub Desktop.
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