Skip to content

Instantly share code, notes, and snippets.

@hayatbiralem
Created November 15, 2018 18:07
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 hayatbiralem/19e2085418f2cd3a30e34e411102a965 to your computer and use it in GitHub Desktop.
Save hayatbiralem/19e2085418f2cd3a30e34e411102a965 to your computer and use it in GitHub Desktop.
Remove empty arrays from nested array
<?php
$array1 = $array2 = array (
0 =>
array (
'id' => '',
'name' => '',
'description' => null,
'categories' => false,
'posts' => '',
),
1 => array(
'asd' => '',
'foo' => [
'bar' => [
'baz' => ''
]
]
)
);
$array2[0]['id'] = 5;
function remove_empty_values($array){
if(is_array($array)) {
$json_encoded_arr = json_encode($array, JSON_UNESCAPED_UNICODE);
} else {
$json_encoded_arr = $array;
}
$re = '/\,?"[^"]*":""/m';
$json_encoded_arr = str_replace('{}', '""', $json_encoded_arr);
if(preg_match($re, $json_encoded_arr)){
$json_encoded_arr = preg_replace($re, '', $json_encoded_arr);
return remove_empty_values($json_encoded_arr);
}
return array_filter(array_map(function ($val){ return array_filter((array) $val); }, (array)json_decode($json_encoded_arr, true)));
}
$array_clean1 = remove_empty_values( $array1 );
$array_clean2 = remove_empty_values( $array2 );
echo '<pre>';
var_export( $array_clean1 );
echo '</pre>';
echo '<pre>';
var_export( $array_clean2 );
echo '</pre>';
/** Outputs
array (
)
array (
0 =>
array (
'id' => 5,
),
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment