Posted By

BilalELMoussaoui on 07/20/11


Tagged

php remove arrays null values


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


remove null values in array


 / Published in: PHP
 

remove all nulls values in an array

  1. /*
  2.  * remove null value from array
  3.  * @param: array $array the array you will be remove the null value
  4.  * @param: boolean $lessKeys less the keys of array
  5.  * @return: array the new array
  6. */
  7. function array_remove_null($array,$lessKeys = true){
  8. $NewArray = array();
  9. try{
  10. if(is_array($array)){
  11. $array = array_map('trim',$array);
  12. if(is_bool($lessKeys)){
  13. foreach($array as $key => $value){
  14. if(($value != null || strlen($value) != 0) && $lessKeys === true){
  15. $NewArray[$key] = $value;
  16. }elseif($value){
  17. $NewArray[] = $value;
  18. }
  19. }
  20. return $NewArray;
  21. }else{
  22. throw new Exception('array_remove_null() expects parameter 2 to be boolean, ' . gettype( $lessKeys ) . ' given', E_USER_WARNING );
  23. }
  24. }else{
  25. throw new Exception('array_remove_null() expects parameter 1 to be array, ' . gettype( $array ) . ' given', E_USER_WARNING );
  26. }
  27. }catch(Exception $e){
  28. trigger_error($e->getMessage(),E_USER_WARNING);
  29. }
  30. }

Report this snippet  

You need to login to post a comment.