» Birthday Bundle - Over $400 worth of Envato files for just $20

PHP: Equivalent of trim() Function for Arrays

Posted on October 5, 2008, Filled under PHP,  Bookmark it

This function strips the null element values from the beginning and ending of an array. For instance, this snippet is useful when you use file(), which reads an entire file into an array and in the beginning / ending of the file there are blank lines that need to be stripped.

function trim_array($array, $keep_keys = false)
{
$i = 0;

   foreach($array as $key => $value)
   {
   $value = trim($value);

   if($value) break;

if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, 0, $i);
}

$reverse = array_reverse($array, true);

$i = 0;

   foreach($reverse as $key => $value)
   {
   $value = trim($value);

   if($value) break;

   if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, -$i);
}

return $array;
}

$array = array(' ', ' ' , ' ', "n", "r", 1, 2 , 5 , 7, ' ', ' ', ' ', 10, 11, 12, 13, ' ', "r", "n", " ", " ");

echo "<pre>"; print_r($array); echo "</pre>";

/*
First Argument: The Array
Second Argument: New keys? false = the current keys will be kept, true= new keys will be assigned to the array (default is set to 'false')
*/

echo "<pre>"; print_r(trim_array($array, true)); echo "</pre>";

NOTE: In the second argument of trim_array() you can specify if you wish to keep the initial array keys (true = will keep the keys, false = will assign new ones). The default value is ‘false’, meaning that new keys will be assigned to the array.

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

2 Replies to "PHP: Equivalent of trim() Function for Arrays"

  1. If you want to remove empty elements from an array? Just do this.

    $a = array ('a', 'b', ' ', 'c', 'd', '');
    $a = implode(',', $a);
    $a = preg_split("~,~",  $a ,  -1,  PREG_SPLIT_NO_EMPTY);
    print_r($a);
    // Array ( [0] => a [1] => b [2] => [3] => c [4] => d )
    

    If you don’t care about keeping keys.

  2. hey ausome 1
    that was awesome
    i have been looking for this for like an hour!

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)