Last active
January 6, 2025 12:59
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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