Skip to content

Instantly share code, notes, and snippets.

@vijinho
Last active January 6, 2025 12:59
Show Gist options
  • Save vijinho/730b3f291fbb45e08e8c7ff9d473b91f to your computer and use it in GitHub Desktop.
Save vijinho/730b3f291fbb45e08e8c7ff9d473b91f to your computer and use it in GitHub Desktop.
Function in PHP to throw out empty values from an array (and optional drop values which have specified keys passed-in)
<?php
/**
* Clear an array of empty values and specified keys
*
* @param array $keys array keys to explicitly remove regardless
* @return array the trimmed down array
*/
function array_clear($array, $keys = [])
{
foreach ($array as $key => $value) {
if (is_array($value)) {
// Recursively clear any nested arrays
$value = array_clear($value, $keys);
}
// Remove empty values and specified keys
if (empty($value) && 0 !== $value || in_array($key, $keys, true)) {
unset($array[$key]);
}
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment