25 August, 2010

Unset empty elements in Array

It is quite easier to unset empty element(s) in an array in php. Following code will do the work.

//this is a test array
$testArr = array(1 => "First", 2 => "", 3 => "Third", 4 => "", 5 =>"Fifth");
//loop through the array and remove empty elements
foreach($testArr as $key => $value) {
if(empty($value)) {
unset($testArr[$key]);
}
}
//view the array with empty elements removed
print_r($testArr);
?>

1 comment:

Drew said...

array_filter, Done!