How to remove empty entries in an array?

I am collecting a user's name from a web form, and parse out the form field into salutation, first name, middle name, and last name if they are present. Here is the code snippet used to extract the name parts:

$parts = explode(" ", $_POST['name']);

//To remove elements from the $parts array:
$parts = array_filter($parts);

// The code above removes elements with values "", null, 
// 0, false and "0". To filter only empty values, use:
$parts = array_filter($parts, function($x) { !empty($x); });

// function(){} only works in php version 5.3 or above.

The array_filter returns elements that returns TRUE if no callback function is supplied.

Tags: 

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.