dev.kanngard.net make sure you visit my new blog at: johankanngard.net

Removing empty elements in a PHP array

by Johan Känngård / [PHP] / 2005-05-12 / #14


This works like the @Trim formula in Notes/Domino.

I'm still new at PHP, so there are maybe better ways of doing this.

/** * Trims an array from empty elements. * * @param $a the array to trim. * @return a new array with the empty elements removed. */ function array_trim($a) { $j = 0; for ($i = 0; $i < count($a); $i++) { if ($a[$i] != "") { $b[$j++] = $a[$i]; } } return $b; }

Use it like this:

$a[0]=""; $a[1]="An entry"; $a[2]="Another one"; $a[3]=""; $b=array_trim($a);

The resulting $b array will have two entries, with the two empty ones removed.