• 0

[PHP] Removing empty elements from an array


Question

5 answers to this question

Recommended Posts

  • 0

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

Link to comment
Share on other sites

  • 0

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

maybe more efficient?

Edited by zzachattack2
Link to comment
Share on other sites

  • 0

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.