squiblo Posted September 5, 2010 Share Posted September 5, 2010 Is there a built in function to remove empty array values for example: change Array ( [0] => Bob [1] => [2] => Ryan [3] => Jane ) to Array ( [0] => Bob [1] => Ryan [2] => Jane ) Thanks Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/ Share on other sites More sharing options...
PaulRyan Posted September 5, 2010 Share Posted September 5, 2010 Hello Squiblo, try the following. $array = array_filter($yourArray); Hopefully that will help you Thanks, Paul. Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/#findComment-1107472 Share on other sites More sharing options...
Pikachu2000 Posted September 5, 2010 Share Posted September 5, 2010 The problem is that array_filter(), on its own, will remove a legitimate array element if it contains a value that equates to FALSE, such as a zero. Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/#findComment-1107480 Share on other sites More sharing options...
PaulRyan Posted September 5, 2010 Share Posted September 5, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/#findComment-1107493 Share on other sites More sharing options...
Alex Posted September 5, 2010 Share Posted September 5, 2010 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); Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/#findComment-1107497 Share on other sites More sharing options...
PaulRyan Posted September 5, 2010 Share Posted September 5, 2010 Ahh right yeah, my bad. Sorry if I caused you any confusion squiblo Paul. Quote Link to comment https://forums.phpfreaks.com/topic/212581-remove-empty-array-value/#findComment-1107500 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.