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!
- October 5, 2008
- article by Gabriel C.
- 2 comments
Related Posts
Equivalent of PHP’s array_combine() functionat October 15, 2008
Equivalent of PHP’s in_array() functionat September 13, 2008 with 6 comments
Display Values from an Array in Random Orderat October 2, 2008
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
Creating the array_isearch() Functionat November 8, 2008

2 Replies to "PHP: Equivalent of trim() Function for Arrays"
October 6, 2008 at 6:15 PM
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.
October 14, 2009 at 12:40 PM
hey ausome 1
that was awesome
i have been looking for this for like an hour!