How to trim white spaces of array values in php

I had trouble with the existing answers when using multidimensional arrays. This solution works for me.

if (is_array($array)) {
    foreach ($array as $key => $val) {
        $array[$key] = trim($val);
    }
}

array_map and trim can do the job

$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);

array_walk() can be used with trim() to trim array

<?php
function trim_value(&$value) 
{ 
    $value = trim($value); 
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

See 2nd example at http://www.php.net/manual/en/function.trim.php


Multidimensional-proof solution:

array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});

Tags:

Php

Arrays