Archive

Posts Tagged ‘blank’

Print Array Without Trailing Commas In PHP

April 24th, 2009 No comments

I have previously talked about Removing commas from the end of strings, but it is also possible to use the implode() function to do the same sort of thing.

implode() takes two parameters, the separator and the array, and returns a string with each array item separated with the separator. The following example shows how this function works.

$array = array(1,2,3,4,5,6);
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6". However, things tend to become messy again when you have an array with empty items in it.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6,,". So to solve this issue we need to use the array_filter() function to clear out any blank array items before passing the output to the implode() function. The following example shows this in action.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', array_filter($array));

The $list variable will now contain the string "1,2,3,4,5,6", which is the string we are looking for.

Remove Blank Entries From An Array With PHP

June 2nd, 2008 No comments

If you have an array that you want to remove any null data items from then you can use the following function. It will create a new array and only copy across items from the existing array if they contain a value. If the value is an array the function calls itself and makes sure that the returned array contains something before adding it to the new array.

function array_purge_empty($arr){
 $newarr = array();
 foreach($arr as $key=>$val){
  if(is_array($val)){
   $val = array_remove_empty($val);
   // does the result array contain anything?
   if(count($val)!=0){
    $newarr[$key] = $val;
   }
  }else{
   if(trim($val) != "){
    $newarr[$key] = $val;
   }
  }
 }
 return $newarr;
}

Here is an example of the function in action.

// create array with some null items in it.
$array = array('a','b'=>'',3,0,' ',NULL,'',array(),array(1),4);
// print array
echo '<pre>'.print_r($array,true).'</pre>';
// print result of array_purge_empty() function
echo '<pre>'.print_r(array_purge_empty($array),true).'</pre>';

This produces the following output.
Array
(
 [0] => a
 [b] =>
 [1] => 3
 [2] => 0
 [3] =>
 [4] =>
 [5] =>
 [6] => Array
  (
  )
 
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)
 
Array
(
 [0] => a
 [1] => 3
 [2] => 0
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)

Categories: PHP Arrays Tags: , , , , ,