Jump to content

Remove empty array value


squiblo

Recommended Posts

By his example I was going by an array of names which usually doesn't have anything equating to FALSE.

 

The following will work and remove any values that are not set, but keep values like ZERO.

 

<?PHP
// This is your starting array
$oldArray = array('Bob','2','Ryan','Jane','0','false','');

//Initialize a new array to add elements too
$newArray = array();

// Loop through original array to filter out empty elements
foreach($oldArray as $arrayElement) {
  if(isset($arrayElement)) {
    // Only add elements that have content
    array_push($newArray,$arrayElement);
  }
}

print_r($newArray);

?>

 

The above should do the trick.

 

Regards, Paul.

That won't work either. You're looping through an array's values, so all of the values will be set, so nothing will ever be removed. Instead you can do it like this:

 

$arr = array('Bob','2','Ryan','Jane','0','false','');
foreach($arr as $key => $val) {
if($val === '') {
	unset($arr[$key]);
}
}
print_r($arr);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.