php trim array values

This article we will explain how to trim array values using different ways in PHP .

Consider the example

$array = array('one', 
               ' two', 
               ' three ', 
               '       four', 
               'five            ',
               '      six         '
              );

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(4) " two"
  [2]=>
  string(7) " three "
  [3]=>
  string(11) "       four"
  [4]=>
  string(16) "five            "
  [5]=>
  string(18) "      six         "
}

We can trim the above declared array values in below mentioned three ways.

1)Trim array values using array_map and trim functions

$trimmed_array=array_map('trim',$array );
var_dump($trimmed_array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}

2) Trim array values using foreach

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

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}

3) Trim array values using array_walk

function array_trim(&$value) 
{ 
    $value = trim($value); 
}

array_walk($array, 'array_trim');

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}

 

 

Leave a Reply

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