How to trim array elements in PHP in one shot

Posted by Stanislav Furman  on April 17, 2013

If you are looking for a method to trim leading and trailing white spaces in all elements of a PHP array, you could use the following code:


<?php
// custom function to trim value
function _trim(&$value) 
{
    $value = trim($value);    
}

$data = array('  a  ',' b',' c   d ');
array_walk($data,"_trim");

var_dump($data);

/*
Output:
array (size=3)
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)
  2 => string 'c   d' (length=5)

*/

This works, but might look a little long. If you want a shorter solution, here it is:


<?php
array_walk($arr, create_function('&$val', '$val = trim($val);')); 

Enjoy!


Comments

Jean Frederic Nault says:
May 18, 2014 at 02:07 am
I use : $array = array_filter(array_map('trim', explode("\n", $string)), 'strlen');
Flag as SPAM  |  Permalink

Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.