Skip to content

Instantly share code, notes, and snippets.

@sectsect
Created August 29, 2017 15:35
Show Gist options
  • Save sectsect/c8491d99ee557fa1f37d04688165ee18 to your computer and use it in GitHub Desktop.
Save sectsect/c8491d99ee557fa1f37d04688165ee18 to your computer and use it in GitHub Desktop.
The strict empty check for PHP array
<?php
function array_remove_empty( $array ) {
foreach ( $array as $key => $value ) {
if ( is_array($value) ) {
$array[$key] = array_remove_empty( $array[$key] );
}
if ( empty( $array[$key] ) ) {
unset( $array[$key] );
}
}
return $array;
}
function is_array_empty( $array ) {
$array = array_remove_empty( $array ); // Remove empty array
$array = array_filter( (array) $array );
if ( empty($array) ) {
return true;
} else {
return false;
}
}
@sectsect
Copy link
Author

Usage Example

$raw = array(
	'firstname' => 'Foo',
	'lastname'  => 'Bar',
	'nickname' => '',
	'birthdate' => array(
		'day'   => '',
		'month' => '',
		'year'  => '',
	),
	'likes' => array(
		'cars'  => array('Subaru Impreza WRX STi', 'Mitsubishi Evo', 'Nissan GTR'),
		'bikes' => array(),
	),
);
if ( ! is_array_empty( $array ) ) {
	// Exists!!
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment