Scott Boms

Trim Empty Values From An Array

As part of a project I’m in the midst of, I needed to be able to take an array which may have one or more keys with empty values and remove those elements from the array in order to find it’s true length. In this case, I didn’t care about the actual data in the array, just the count() value returned.

After searching through the PHP documentation, I didn’t see any internal functions or methods that would do exactly what I needed, so out to Google I went and after a bit of searching, refining my query and testing, I found the solution which I thought I would share — if nothing else, because I hope it makes it easier for others to find.

The code looks like this:


// @param $a = array passed into the function
// @param $b = result returned

function array_trim($a) {
  $j = 0;
  for($i = 0; $i < count($a); $i++) {
    if($a[$i] != "") {
      $b[$j++] = $a[$i];
    }
  }
  return $b;
}

$b = array_trim($my-array-to-trim);

Simply create a variable, and then pass your array to be trimmed through the function. It takes care of the rest and will output a nicely compressed array of key/value pairs. The empty key/value pairs are removed whether they are at the start, middle or end of the array.

Of course, if there’s a better way, I’m open to suggestions!

So say you…

This will take the array (by reference, which means any alterations will be made in the original array as well), and remove blank values

function array_trim(&$array) {
  for($i = 0; $i &lt; count($array); $i++) {
  if(strlen($array[$i]) == 0)
    unset($array[$i]);  //removes from array
  }
  reset($array); //resets pointer to beginning
}

array_trim($my_array_to_trim);
$number_of_non_blank_values=count($my_array_to_trim);

This way you also have the values if you need them also… only one created variable ($i)

John O John O March 25, 2006

Wow the formatting came out like crap! there should be /asterisk and asterisk/ and underscores in there :P

John O John O March 25, 2006

Thanks John. Strangely enough, the formatting looked better in the e-mail notification sent by MT. I’ll give it a shot and see if there’s any performance improvement. Faster is better.

Scott Scott March 25, 2006

Here is some code that I wrote that I have been using for a while. It supports multi-dimensional arrays and weird occurrences where a value is just a space. Hope this helps.

function clean_array ($array) {
  foreach ($array as $key => $value) {
    if(is_array($value)) {
      $array[$key] = clean_array($value);
    } else {
      if ($value == NULL or $value == " ") {
        unset($array[$key]);
      }
    }
  }
  return $array;
}

Michael Simmons Michael Simmons March 25, 2006

No problem. You won’t see a performance improvement under normal circumstances. But if you end up with 1,000+ calls quickly, it’ll improve everything.

John O John O March 25, 2006