Clean a PHP array

Clean a PHP arrayI have spoken a little about arrays in the past, but I feel it important to describe methods to clear and clean an array using PHP. The following tutorial will show you how to do the following:

  1. Ensure that the string is an array
  2. Remove empty values from an array
  3. Remove duplicate values from an array

The above list may or may not always be appropriate. In some instances, you may want to retain empty or duplicate values. In which case you could omit certain parts of the following function.

Clean Array Function

Firstly, for the sake of this tutorial let’s create an array and populate it with data:

$my_array = array("php", "javascript", "asp", "html", "", "php", "css", "html");

This will return:

Array
(
    [0] => php
    [1] => javascript
    [2] => asp
    [3] => html
    [4] =>
    [4] => php
    [4] => css
    [4] => html
)

As you can see from the above example, this array contains a few duplicate parts as well as an empty value. Let’s remove all non-unique values (duplicates) from $my_array:

$my_array = array("php", "javascript", "asp", "html", "", "php", "css", "html");
$my_array = array_unique($my_array);  // REMOVE DUPLICATES

Now we can remove the empty values from the array:

$my_array = preg_grep('#S#', array_map('trim', $my_array)); // REMOVE EMPTY VALUES

If you are going to use this clean-up method on a regular basis, you might want to consider putting it into a function so that you can call on it with ease.

/// CLEAN ARRAY
function clean_array($array,$delimiter)
{
	if(!is_array($array)) { $array = explode($delimiter, $array); }
	$array = array_unique($array);
	return preg_grep('#S#', array_map('trim', $array));
}
///

Notice that I have added another line to this function:

if(!is_array($array)) { $array = explode($delimiter, $array); }

This will check to ensure that the array is an array and not just a list of delimited numbers. There is also another string added to the function to select the method of delimitation. In our example, we used a ‘,’ to delimit the array. So this is how we could use this array:

$my_array = array("php", "javascript", "asp", "html", "", "php", "css", "html");
$my_array = clean_array($my_array, ",");

or…

$my_array = clean_array(array("php", "javascript", "asp", "html", "", "php", "css", "html"), ",");

This would return the much cleaner array:

Array
(
    [0] => php
    [1] => javascript
    [2] => asp
    [3] => html
    [4] => css
)

Leave a Reply

Your email address will not be published. Required fields are marked *