Skip to content

Instantly share code, notes, and snippets.

@aldolat
Created May 21, 2017 05:34
Show Gist options
  • Save aldolat/849846a0238645e0d32f09a8221217c7 to your computer and use it in GitHub Desktop.
Save aldolat/849846a0238645e0d32f09a8221217c7 to your computer and use it in GitHub Desktop.
Remove empty keys from an array recursively.
<?php
/**
* Remove empty keys from an array recursively.
*
* @param array $array The array to be checked.
* @param boolean $make_empty If the output is to return as an empty string.
* @since 1.29
* @see http://stackoverflow.com/questions/7696548/php-how-to-remove-empty-entries-of-an-array-recursively
*/
function pis_array_remove_empty_keys( $array, $make_empty = false ) {
if ( ! is_array( $array ) ) {
return;
}
foreach ( $array as $key => $value ) {
if ( is_array( $value ) ) {
$array[$key] = pis_array_remove_empty_keys( $array[$key] );
}
if ( empty( $array[$key] ) ) {
unset( $array[$key] );
}
}
if ( empty( $array ) && $make_empty ) {
$array = '';
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment