Skip to content

Instantly share code, notes, and snippets.

@iBet7o
Last active August 29, 2015 14:03
Show Gist options
  • Save iBet7o/14d9059a47bf4e9e2e3c to your computer and use it in GitHub Desktop.
Save iBet7o/14d9059a47bf4e9e2e3c to your computer and use it in GitHub Desktop.
Eliminar elementos vacíos de un arreglo con PHP

Función para eliminar los elementos vacíos de un arreglo, en PHP, soporta arreglos anidados.

La función:

function removeEmptyElements(&$element)
{
    if (is_array($element)) {
        if ($key = key($element)) {
            $element[$key] = array_filter($element);
        }

        if (count($element) != count($element, COUNT_RECURSIVE)) {
            $element = array_filter(current($element), __FUNCTION__);
        }

        $element = array_filter($element);

        return $element;
    } else {
        return empty($element) ? false : $element;
    }
}

Ejemplo de uso:

$data = array(
    'horarios' => array(),
    'grupos' => array(
        '1A' => array(
            'Juan' => array(
                'calificaciones' => array(
                    'Matematicas' => 8,
                    'Español' => 5,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => 10,
                    'marzo' => '',
                )
            ),
            'Damian' => array(
                'calificaciones' => array(
                    'Matematicas' => 10,
                    'Español' => '',
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => '',
                    'marzo' => 5,
                )
            ),
        ),
        '1B' => array(
            'Mariana' => array(
                'calificaciones' => array(
                    'Matematicas' => null,
                    'Español' => 7,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => null,
                    'febrero' => 5,
                    'marzo' => 5,
                )
            ),
        ),
    )
);

$data = array_filter($data, 'removeEmptyElements');

var_dump($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment