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.

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.