Return to Snippet

Revision: 49339
at July 20, 2011 07:50 by BilalELMoussaoui


Initial Code
/*
 * remove null value from array
 * @param: array $array the array you will be remove the null value
 * @param: boolean $lessKeys less the keys of array
 * @return: array the new array
*/
function array_remove_null($array,$lessKeys = true){
    $NewArray = array();
    try{
        if(is_array($array)){
            $array = array_map('trim',$array); 
                if(is_bool($lessKeys)){
                    foreach($array as $key => $value){
                        if(($value != null || strlen($value) != 0) && $lessKeys === true){
                            $NewArray[$key] = $value;
                        }elseif($value){
                            $NewArray[] = $value;
                        }
                    }
                    return $NewArray;
                }else{
                    throw new Exception('array_remove_null() expects parameter 2 to be boolean, ' . gettype( $lessKeys ) . ' given', E_USER_WARNING );
                }
        }else{
            throw new Exception('array_remove_null() expects parameter 1 to be array, ' . gettype( $array ) . ' given', E_USER_WARNING );
        }
    }catch(Exception $e){
        trigger_error($e->getMessage(),E_USER_WARNING);
    }
}

Initial URL


Initial Description
remove all nulls values in an array

Initial Title
remove null values in array

Initial Tags
php

Initial Language
PHP