configure Veteran Posted September 17, 2004 Veteran Share Posted September 17, 2004 How do you remove empty elements from an array? Link to comment Share on other sites More sharing options...
0 configure Veteran Posted September 17, 2004 Author Veteran Share Posted September 17, 2004 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 More sharing options...
0 zzachattack2 Posted September 17, 2004 Share Posted September 17, 2004 (edited) foreach($array as $key => $value) { ?if($value == "" || $value == NULL) ?{ ? ?unset($array[$key]); ?} } $newarray = array_values($array); maybe more efficient? Edited September 17, 2004 by zzachattack2 Link to comment Share on other sites More sharing options...
0 configure Veteran Posted September 17, 2004 Author Veteran Share Posted September 17, 2004 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 More sharing options...
0 zzachattack2 Posted September 17, 2004 Share Posted September 17, 2004 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 More sharing options...
0 configure Veteran Posted September 17, 2004 Author Veteran Share Posted September 17, 2004 Got it foreach($var as $key => $value) { $var[$key] = trim($value); if($var[$key] == "") { unset ($var[$key]); } } Thanks :) Link to comment Share on other sites More sharing options...
Question
configure Veteran
How do you remove empty elements from an array?
Link to comment
Share on other sites
5 answers to this question
Recommended Posts