• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

[PHP] Removing empty elements from an array

Question

configure    1

How do you remove empty elements from an array?

Share this post


Link to post
Share on other sites

5 answers to this question

Recommended Posts

  • 0
configure    1

This is what I've got, please let me know if you have a better way of doing it.

foreach($var as $key => $value) {
$var[$key] = trim($value);
}

	$var = array_unique($var);

	$key = array_search('', $var);

	if($key != "") array_splice($var, $key,1);

Share this post


Link to post
Share on other sites
  • 0
zzachattack2    0

foreach($array as $key => $value) 
{ 
 ?if($value == "" || $value == NULL) 
 ?{ 
 ? ?unset($array[$key]); 
 ?} 
} 
$newarray = array_values($array);

maybe more efficient?

Edited by zzachattack2

Share this post


Link to post
Share on other sites
  • 0
configure    1

What if I also want to trim the element as well? I tried this but it doesn't work, any idea why?

 foreach($var as $key => $value) {
  $var[$key] = trim($value);

 	 if($value == "" || $value == NULL) {
 	 unset ($var[$key]);
 	 }
  }

Share this post


Link to post
Share on other sites
  • 0
zzachattack2    0

try adding the line $newarray = array_values($var); it should recreate the index for the array $var, because i believe after removing variables from an array your array doesn't reindex itself, but just skips numbers. So if $var[2] had a blank values and after removing empty values from an array, the array would have the structure: 0, 1, 3, 4, etc.

Share this post


Link to post
Share on other sites
  • 0
configure    1

Got it

 foreach($var as $key => $value) {
  $var[$key] = trim($value);

 	 if($var[$key] == "") {
 	 unset ($var[$key]);
 	 }
  }

Thanks :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.