remove null values in array


/ Published in: PHP
Save to your folder(s)

remove all nulls values in an array


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.