Removing empty elements from an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Removing empty elements from an array

Post by kettle_drum »

ANybody know how i can remove empty elements from an array?

I.e i have:

Code: Select all

Array ( ї0] => )
and count() says there is one item in the array - but its empty.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

something like this

Code: Select all

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

Mark
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

As far as I know there is not a remove empty array function so you have to step through the array. Two possibilities spring to mind.

1) use the command array_filter
2) use a foreach/while with array_shift and build a new array.

Out of preference I would use option 1.

Regards
Post Reply